4
此问题受this question启发。 我理解这个例子(ListBuilder
),但我一直无法为我的状态monad创建一个while
循环。我不清楚如何bind
while
循环的主体,因为迭代是一个又一个。State Monad - While-loops
谢谢。
/////////////////////////////////////////////////////////////////////////////////////
// Definition of the state
/////////////////////////////////////////////////////////////////////////////////////
type StateFunc<'State, 'T> = 'State -> 'T * 'State
/////////////////////////////////////////////////////////////////////////////////////
// Definition of the State monad
/////////////////////////////////////////////////////////////////////////////////////
type StateMonadBuilder<'State>() =
// M<'T> -> M<'T>
member b.ReturnFrom a : StateFunc<'State, 'T> = a
// 'T -> M<'T>
member b.Return a : StateFunc<'State, 'T> = (fun s -> a, s)
// M<'T> * ('T -> M<'U>) -> M<'U>
member b.Bind(p : StateFunc<_, 'T>, rest : 'T -> StateFunc<_,_>) : StateFunc<'State, 'U> =
(fun s ->
let a, s' = p s
rest a s')
member b.Zero() = fun s ->(), s
member b.Delay f = f
member b.Run f = f()
// Getter for the whole state, this type signature is because it passes along the state & returns the state
member b.getState : StateFunc<'State, _> = (fun s -> s, s)
// Setter for the state
member b.putState (s:'State) : StateFunc<'State, _> = (fun _ ->(), s)
// (unit -> bool) * M<'T> -> M<'T>
member b.While (cond, body: StateFunc<'State, _>): StateFunc<'State, _> =
(fun s ->
if cond() then
let bind =
let _, s' = body s
fun s' -> body s'
b.While (cond, bind) // This is wrong
else
body s)
您的示例代码似乎来自[ExtCore](https://github.com/jack-帕帕斯/ ExtCore)。你看过那里的代码,看它是否包含'StateBuilder'类型的'While'成员的定义? –
太棒了。我在https://github.com/jack-pappas/ExtCore/blob/master/ExtCore/Control.fs找到了一个。谢谢。 – NoIdeaHowToFixThis