gpt4 book ai didi

haskell - STRef 和幻像类型

转载 作者:行者123 更新时间:2023-12-04 07:37:26 24 4
gpt4 key购买 nike

是否 sSTRef s a用具体类型实例化?可以很容易地想象一些代码,其中 STRefa 的上下文中使用承担Int .但是类型推断似乎没有任何东西可以给出 s一种具体的类型。

想象一下伪 Java 中的一些东西,例如 MyList<S, A> .即使S从未出现在 MyList 的执行中实例化一个具体类型,如 MyList<S, Integer>其中未使用具体类型代替 S没有意义。那怎么能STRef s a工作?

最佳答案

tl;dr - 实际上它似乎总是被初始化为 RealWorld到底

source注意到 s可以实例化为 RealWorld stToIO 的内部调用,但在其他方面未实例化:

-- The s parameter is either

-- an uninstantiated type variable (inside invocations of 'runST'), or

-- 'RealWorld' (inside invocations of 'Control.Monad.ST.stToIO').



查看 ST 的实际代码然而似乎 runST使用特定值 realWorld# :
newtype ST s a = ST (STRep s a)
type STRep s a = State# s -> (# State# s, a #)

runST :: (forall s. ST s a) -> a
runST st = runSTRep (case st of { ST st_rep -> st_rep })

runSTRep :: (forall s. STRep s a) -> a
runSTRep st_rep = case st_rep realWorld# of
(# _, r #) -> r
realWorld#定义为 magic primitive inside the GHC source code :
realWorldName     = mkWiredInIdName gHC_PRIM  (fsLit "realWorld#")
realWorldPrimIdKey realWorldPrimId

realWorldPrimId :: Id -- :: State# RealWorld
realWorldPrimId = pcMiscPrelId realWorldName realWorldStatePrimTy
(noCafIdInfo `setUnfoldingInfo` evaldUnfolding
`setOneShotInfo` stateHackOneShot)

您也可以在 ghci 中确认。 :
Prelude> :set -XMagicHash
Prelude> :m +GHC.Prim
Prelude GHC.Prim> :t realWorld#
realWorld# :: State# RealWorld

关于haskell - STRef 和幻像类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26249297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com