【发布时间】:2016-09-17 00:49:52
【问题描述】:
我想我了解 State Monad 的运作方式。我已经设法编写了一些使用 State Monad 的代码。
我了解 State 的 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 将 do 表示法转换为函数。
【问题讨论】:
标签: haskell functional-programming monads state-monad