State Monad - While-loops

This question was inspired by this question . I understand the example ( ListBuilder), but I was not able to create a loop whilefor my state monad. It’s not clear to me how the bindbody of the loop is while, since iterations follow one after another.

Thanks.

/////////////////////////////////////////////////////////////////////////////////////
// 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)
+4
source share
1 answer

If you look at the various calculation builders in ExtCore , there is one interesting thing - for any monad, the implementation While(and also For) of the member is usually the same.

, Bind, Zero While. , , - ( M<_> ):

// (unit -> bool) * M<'T> -> M<'T>
member this.While (guard, body : M<_>) : M<_> =
    if guard () then
        this.Bind (body, (fun () -> this.While (guard, body)))
    else
        this.Zero ()

- - , While, .

, , F # - F # , , , Haskell , , ( , ExtCore, - ). , , , , ...

+4

Source: https://habr.com/ru/post/1523912/


All Articles