Is there a name for for this "stateful function with result" pattern? An abstraction for it in FSharpPlus?

140 views Asked by At

I have a function of type 'state -> 'event -> Result<'state * 'result, 'error>. I have a starting 'state and 'event list.

I'd like to fold over the events and get the final state and list of results produced if all folds were okay, or the first error.

I could write a computation expression or fold for it, but was wondering if there was a name for this pattern? Is there something I could use out-of-the-box from FSharpPlus? It seems close to a state monad, but the state and result are both wrapped inside a Result type, so it's sort of a state + result monad?

1

There are 1 answers

2
Gus On BEST ANSWER

As @carsten already pointed, you have StateT available in F#+

You have:

'state -> 'event -> Result<'state * 'result, 'error>

Now let's swap some parameters:

'event -> 'state -> Result<'result * 'state, 'error>

this can be expressed as

StateT<'state, Result<'result * 'state, 'error> in current F#+ StateT encoding.

So, let's call your function f and let's pretend you have events which is an list<'event> (or actually any other traversable structure of events) , now you can do this:

#r "nuget: FSharpPlus, 1.2"
open FSharpPlus
open FSharpPlus.Data

// your code for 'f', 'events' and `initialState` definition goes here

let foldedStateT : StateT<'state, Result<'result * 'state, 'error> =
    events |> traverse (fun x -> StateT (f x))

let finalResult = StateT.run foldedStateT initialState