Search code examples
f#state-monad

What are the advantages of a wrapped up the state monad?


This one may be a stupid one but, having a look at (Eliminating my explicit state passing via like, monads and stuff)

type State<'s,'a> = State of ('s -> 'a * 's)

type StateBuilder<'s>() =
  member x.Return v : State<'s,_> = State(fun s -> v,s)
  member x.Bind(State v, f) : State<'s,_> =
    State(fun s ->
      let (a,s) = v s
      let (State v') = f a
      v' s)

let withState<'s> = StateBuilder<'s>()

let getState = State(fun s -> s,s)
let putState v = State(fun _ -> (),v)

let runState (State f) init = f init

what are the advantages of wrapping 's -> 'a * 's in State. Is it just a safety precaution?


Solution

  • I think it's more a matter of preference or convenience than safety; some people like to wrap the function in a single-case discriminated union type like that, and some don't.

    I prefer not to wrap the functions, because it introduces a small amount of additional overhead and can inhibit the compiler from making some optimizations. In my ExtCore library, I've implemented the same thing, using a type alias instead of creating an actual type to wrap the function:

    type StateFunc<'State, 'T> = 'State -> 'T * 'State