'MutVar#'是什么意思?

Att*_*lah 3 haskell ghc compiler-optimization ghci

我一直在努力阅读和理解实现Haskell的ST monad的代码,我找到了这段代码:

{-# 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  :  cvs-ghc@haskell.org
-- 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 a@ is a mutable variable in state thread @s@,
-- containing a value of type @a@

-- |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#)
Run Code Online (Sandbox Code Playgroud)

我在上面的代码文件中看到以下代码行:

data STRef s a = STRef (MutVar# s a)
Run Code Online (Sandbox Code Playgroud)

快速搜索MutVar#产生以下结果:

我的问题是:什么是MutVar#?为什么不在任何地方定义?这是什么意思 ?

Lam*_*iry 7

MutVar#是编译器本身提供的原始类型.它代表一个可变的参考,并且形成的核心IORefSTRef.

通常,任何结尾#都是GHC的实现细节.除非你做低级别的hackery,否则你不必担心它们.大多数这些操作都有包装(如ST),更容易使用.

您可以在GHC手册ghc-prim包中阅读有关这些内容的更多信息.

  • 实际上,任何`____#`名称都是原始类型,如`Int#`等等.你需要`{ - #LANGUAGE MagicHash# - }`来启用它. (2认同)