简体   繁体   English

在MonadState中获得并处于状态

[英]get put and state in MonadState

I looked at the MonadState source code , I don't understand why these 3 functions won't get into dead loop? 我查看了MonadState的源代码 ,我不明白为什么这3个函数不会进入死循环? How does this get evaluated? 这是如何评估的?

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

The definitions of get,put,state in the class declaration are the default implementations, which are meant to be overridden in actual instances of the class. 声明中get,put,state的定义是默认实现,它们意味着在类的实际实例中被覆盖。 In this way, the dead loop is broken: if an instance defines only state , then get and put are defined in terms of it using the default implementation in the class. 通过这种方式,死循环被破坏:如果实例仅定义了state ,则使用类中的默认实现来定义getput Similarly, if an instance defines get and put , then state is defaulted. 同样,如果实例定义了getput ,那么state是默认的。

For instance, the Eq type class might have been defined as follows: 例如, 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

It is indeed common to have default self-referring implementations which evaluate to bottom unless something is redefined in the instances. 除非在实例中重新定义某些内容,否则默认的自引用实现确实很常见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM