一般来说,我是 Monads 和 Haskell 的新手,并试图了解如何在使用它们时返回一个值。我的代码如下所示:
foo :: A -> B
foo a = do b <- fooC a (C 0)
-- want to return just (B "b")
fooC :: A -> C -> State MyState B
fooC a c = return (B "b")
我尝试使用snd (snd b)
,但显然State MyState B
不是元组?如何返回所需的值(B "b")
?
编辑:考虑到丹尼尔的建议,重写看起来像这样:
data MyState = MyState String
data C = C Int
foo :: String -> String
-- want to return just "b"
foo a = evalState (fooC a) (C 0)
fooC :: String -> Int -> State MyState String
fooC a c = return "b"
这仍然会导致编译错误:
Couldn't match expected type `State s0 String'
with actual type `Int -> State MyState String'
In the return type of a call of `fooC'
Probable cause: `fooC' is applied to too few arguments
In the first argument of `evalState', namely `(fooC a)'
In the expression: evalState (fooC a) (C 0)
编辑2:固定!最终版本如下所示:
import Control.Monad.State
data MyState = MyState String
data C = C Int
foo :: String -> String
-- want to return just (B "b")
foo a = evalState (fooC a (C 0)) (MyState "whatever")
fooC :: String -> C -> State MyState String
fooC a c = return "b"
main = print(foo("test"))
-- prints "b"