【发布时间】:2018-07-04 23:04:35
【问题描述】:
我试图弄清楚 Monad 状态是如何工作的。我正在尝试实现一个获取两个坐标(x, y) 并返回x 或y 坐标的函数。这应该发生在 State Monad 中。
data Coordin = Coordin {x,y :: Float}
应该实现的功能如下所示:
getX :: State Coordin Float
getY :: State Coordin Float
这怎么解决?
我试过这个:
newtype State s a = State { runState :: s -> (a,s) }
getX:: State Coordin Float
getX = State $ \(x, y) -> (x, (x, y))
但收到此错误消息:
Couldn't match type ‘(Float, t0)’ with ‘Coordin’
Expected type: State Coordin Float
Actual type: State (Float, t0) Float
In the expression: State $ \ (x, y) -> (x, (x, y))
In an equation for ‘getX’: getX = State $ \ (x, y) -> (x, (x, y))
【问题讨论】:
-
是的,你可以这样做。您尝试过什么了吗?
-
是的,但我只是失败了。我试过这个: newtype State sa = State { runState :: s -> (a,s) } getX:: State Coordin Float getX = State $ (x, y) -> (x, (x, y))
-
好的,现在将其添加到问题中并解释问题所在。
-
是的,我做到了。我复制错误信息
标签: haskell functional-programming monads state-monad