我一直試圖閱讀和理解,實現Haskell的ST單子, 代碼,我發現this code:'MutVar#'是什麼意思?
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.STRef
-- Copyright : (c) The University of Glasgow, 1994-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- References in the 'ST' monad.
--
-----------------------------------------------------------------------------
module GHC.STRef (
STRef(..),
newSTRef, readSTRef, writeSTRef
) where
import GHC.ST
import GHC.Base
data STRef s a = STRef (MutVar# s a)
--^a value of type @STRef s [email protected] is a mutable variable in state thread @[email protected],
-- containing a value of type @[email protected]
-- |Build a new 'STRef' in the current state thread
newSTRef :: a -> ST s (STRef s a)
newSTRef init = ST $ \s1# ->
case newMutVar# init s1# of { (# s2#, var# #) ->
(# s2#, STRef var# #) }
-- |Read the value of an 'STRef'
readSTRef :: STRef s a -> ST s a
readSTRef (STRef var#) = ST $ \s1# -> readMutVar# var# s1#
-- |Write a new value into an 'STRef'
writeSTRef :: STRef s a -> a -> ST s()
writeSTRef (STRef var#) val = ST $ \s1# ->
case writeMutVar# var# val s1# of { s2# ->
(# s2#,() #) }
-- Just pointer equality on mutable references:
instance Eq (STRef s a) where
STRef v1# == STRef v2# = isTrue# (sameMutVar# v1# v2#)
我看到了下面這行代碼在上面的代碼文件:
data STRef s a = STRef (MutVar# s a)
上MutVar#
快速搜索,得到以下結果:
- https://hackage.haskell.org/package/primitive-0.4.1/docs/src/Data-Primitive-MutVar.html#MutVar
- https://github.com/ghc/ghc/blob/228ddb95ee137e7cef02dcfe2521233892dd61e0/utils/genprimopcode/Main.hs#L816
我的問題是: 什麼是MutVar#
?爲什麼它沒有在任何地方定義?這是什麼意思 ?
它似乎是一種原始類型[在GHC中定義](https://github.com/ghc/ghc/blob/90dd11bf1918485f0f19bb2fb764f1675c0f0dd5/compiler/prelude/primops.txt.pp#L1868)。它與用於'IORef's的類型相同,'s'類型參數設置爲'RealWorld#'。 – Cactus
它*是*在某處定義的:它在'GHC.Prim'中。該定義只是一個空白存根;正如其他人所說,真正的實現是硬編碼到編譯器中的。這是一個低級的特定於GHC的實現細節。一個不同的Haskell編譯器可能會以不同的方式實現它。 – MathematicalOrchid