我想我理解State Monad是如何运作的。我设法写了一些使用State Monad的代码。
我理解Monad实例的运作方式:
instance Monad (State s) where
return x = State $ \s -> (x,s)
(State h) >>= f = State $ \s -> let (a, newState) = h s
(State g) = f a
in g newState
此代码完美无缺:
type PeopleStack = [String]
enterClub :: String -> State PeopleStack String
enterClub name = state $ \xs -> (name ++ " entered club", name:xs)
leaveClub :: State PeopleStack String
leaveClub = state $ \(x:xs) -> ("Someone left the club", xs)
clubAction :: State PeopleStack String
clubAction = do
enterClub "Jose"
enterClub "Thais"
leaveClub
enterClub "Manuel"
然而,当我尝试在绑定函数中编写clubAction时,我似乎无法使它工作。
这就是我的尝试:
let statefulComputation1 = enterClub "Jose"
statefulComputation1 :: State PeopleStack String
runState (statefulComputation1 >>= (enterClub "Manuel") >>= leaveClub) []
我收到此错误:
<interactive>:13:22:
Couldn't match type ‘StateT
PeopleStack Data.Functor.Identity.Identity String’
with ‘String
-> StateT PeopleStack Data.Functor.Identity.Identity a’
Expected type: String
-> StateT PeopleStack Data.Functor.Identity.Identity a
Actual type: State PeopleStack String
Relevant bindings include
it :: (a, PeopleStack) (bound at <interactive>:13:1)
In the second argument of ‘(>>=)’, namely ‘leaveClub’
In the first argument of ‘runState’, namely
‘(state1 >>= leaveClub)’
我的问题是如何使用bind将该表示法转换为函数。
答案 0 :(得分:3)
您需要使用(>>)
代替(>>=)
:
runState (statefulComputation1 >> (enterClub "Manuel") >> leaveClub) []
(enterClub "Manuel")
的类型为State PeopleStack String
,而(>>=)
则需要函数String -> State PeopleStack a
作为其第二个参数。由于您不能使用statefulComputation1
的结果,因此可以将它们与(>>)
结合使用,忽略第一个状态计算的结果。
答案 1 :(得分:2)
绑定运算符右侧的每个项目(&gt;&gt; =)都需要是一个lambda ....,这样就可以了
runState (statefulComputation1 >>= \_ -> enterClub "Manuel" >>= \_ -> leaveClub) []
或者,您可以使用简写(>>)
runState (statefulComputation1 >> enterClub "Manuel" >> leaveClub) []