简体   繁体   English

Haskell State Monad使用修改表示

[英]haskell State Monad put expressed using modify

I need to express put of the State Monad with use of its modify function however I'm getting a 'Could not deduce' error on my following code: 我需要快递 单子国与使用,但是我让我的下面的代码“无法推断”错误的修改功能:

class Monad m => MonadState m s | m -> s where
    get :: m s
    get = modify (\s -> s)

    put :: s -> m ()
    put = modify $ const ()

    modify :: (s -> s) -> m s
    modify f = undefined  --do { x <- get; put (f x) }

(*I did not yet define modify because my implementation in the comment beside it also returned a similar error but then on an expected return type ms instead of the actual return type m () ) (*我尚未定义修改,因为我在注释旁边的实现也返回了类似的错误,但是返回的是预期的返回类型ms而不是实际的返回类型m()

The exact error I'm getting is: 我得到的确切错误是:

Could not deduce (MonadState m ()) arising from a use of 'modify'
from context (MonadState m s)
  bound by the class declaration for 'MonadState'
  at <..>
Possible fix: add an instance declaration for (MonadState m ())
In the expression: modify
In the expression: modify $ const ()
In an equation for 'put': put = modify const ()

However I'm not sure what this error is trying to tell me and what I'm doing wrong here. 但是,我不确定该错误试图告诉我什么,以及我在做什么错。 If anyone could help me out it'd be much appreciated! 如果有人可以帮助我,将不胜感激!

Best regards, Skyfe. 最好的问候,Skyfe。

What const () would do is transform the current state from whatever it is to () . const ()要做的就是将当前状态从当前状态转换为() Since you want this to work on all states, this won't work since it means that it would be changing the state type from s to () . 由于您希望此方法在所有状态下均有效,因此该方法将无效,因为这意味着它将状态类型从s更改为() It also wouldn't quite do what you want it to do. 它也不会完全按照您想要的去做。 You can use the const function, but it'd be better to write it without first. 您可以使用const函数,但最好不要先编写它。 I'd suggest making it pointful and using an explicit lambda: 我建议使其具有针对性并使用显式的lambda:

put :: s -> m ()
put newState = modify (\currentState -> ???)

As a side note, your commented implementation of modify won't work, you'd really need 作为一个侧面说明,您的评论的实施modify将无法正常工作,你真的需要

modify f = do
    x <- get
    let newX = f x
    put x
    return x

However, I would recommend leaving modify out of the class definition, as mtl does, since it's really more desirable to just implement get and put . 但是,我建议像mtl一样,将modify放在类定义之外,因为实际上更需要实现getput This helps you prevent circular definitions. 这可以帮助您防止循环定义。

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

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