在MonadState中获得并处于状态

时间:2014-04-18 07:17:43

标签: haskell

我查看了MonadState source code,我不明白为什么这三个函数不会进入死循环?这是如何评估的?

class Monad m => MonadState s m | m -> s where
    -- | Return the state from the internals of the monad.
    get :: m s
    get = state (\s -> (s, s))

    -- | Replace the state inside the monad.
    put :: s -> m ()
    put s = state (\_ -> ((), s))

    -- | Embed a simple state action into the monad.
    state :: (s -> (a, s)) -> m a
    state f = do
      s <- get
      let ~(a, s') = f s
      put s'
      return a

1 个答案:

答案 0 :(得分:6)

声明中get,put,state的定义是默认实现,它们意味着在类的实际实例中被覆盖。通过这种方式,死循环被破坏:如果实例仅定义state,则使用类中的默认实现来定义getput。同样,如果实例定义getput,那么state将被默认。

例如,Eq类型类可能已定义如下:

class Eq a where
    (==) :: a -> a -> Bool
    x == y = not (x /= y)
    (/=) :: a -> a -> Bool
    x /= y = not (x == y)

instance Eq Bool where
    True  == True  = True
    False == False = True
    _     == _     = False
    -- the (/=) operator is automatically derived
instance Eq () where
    () /= () = False
    -- the (==) operator is automatically derived

除非在实例中重新定义某些内容,否则默认的自引用实现通常会评估为底部。