Search code examples
f#monadscomputation-expression

F# Binding to output while carrying the state


I am trying to use a Computation Expression to build a list of actions. I need to bind to a value that gets returned from the getFood action so that I can register a later step to consume it.

type Food =
    | Chicken
    | Rice

type Step =
    | GetFood of Food
    | Eat of Food
    | Sleep of duration:int

type Plan = Plan of Step list

type PlanBuilder () =

    member this.Bind (plan:Plan, f) =
        f plan
    member this.Yield _ = Plan []
    member this.Run (Plan x) = Plan (List.rev x)

    [<CustomOperation("eat")>]
    member this.Eat (Plan p, food) =
        printfn "Eat"
        Plan ((Eat food)::p)

    [<CustomOperation("sleep")>]
    member this.Sleep (Plan p, duration) =
        printfn "Sleep"
        Plan ((Sleep duration)::p)

let plan = PlanBuilder()

let rng = System.Random(123)


let getFood (Plan p) =
    printfn "GetFood"
    let randomFood = 
        if rng.NextDouble() > 0.5 then
            Food.Chicken
        else
            Food.Rice
    (Plan ((GetFood randomFood)::p)), randomFood

let testPlan =
    plan {
        let! food = getFood // <-- This is what I am trying to get to work
        sleep 10
        eat food
    }

I believe the problem is with the Bind but I can't figure out what it is.

(*
Example result
testPlan =
    (GetFood Chicken,(
        (Sleep 10,(
            EatFood Chicken
        ))
    ))
*)

Solution

  • To make something like this work, you will probably need a type that has a more monadic structure and lets you store any result, rather than just the plan. I would use something like this:

    type Step =
      | GetFood of Food
      | Eat of Food
      | Sleep of duration:int
    
    type Plan<'T> = Plan of Step list * 'T
    

    Now, Plan<'T> represents a computation that produces a value of type 'T and collects a plan along the way. GetFood can produce a plan, but also return the food:

    let getFood () =
      printfn "GetFood"
      let randomFood = 
        if rng.NextDouble() > 0.5 then Food.Chicken
        else Food.Rice
      Plan([GetFood randomFood], randomFood)
    

    Implementing a computation builder is a bit of a black art, but you can now define Bind and your custom operations. To be able to access variables in the argument, it needs to be a function as in the where or select operations:

    type PlanBuilder () =
    
      member this.For (Plan(steps1, res):Plan<'T>, f:'T -> Plan<'R>) : Plan<'R> =
        let (Plan(steps2, res2)) = f res
        Plan(steps1 @ steps2, res2)
    
      member this.Bind (Plan(steps1, res):Plan<'T>, f:'T -> Plan<'R>) : Plan<'R> =
          let (Plan(steps2, res2)) = f res
          Plan(steps1 @ steps2, res2)
      
      member this.Yield x = Plan([], x)
      member this.Return x = Plan([], x)
      member this.Run (Plan(p,r)) = Plan(List.rev p, r)
    
      [<CustomOperation("eat", MaintainsVariableSpace=true)>]
      member this.Eat (Plan(p, r), [<ProjectionParameter>] food) =
          Plan((Eat (food r))::p, r)
    
      [<CustomOperation("sleep", MaintainsVariableSpace=true)>]
      member this.Sleep (Plan(p, r), [<ProjectionParameter>] duration) =
          Plan ((Sleep (duration r))::p, r)
    
    let plan = PlanBuilder()
    

    This actually lets you implement your test plan:

    let testPlan =
      plan {
          let! food = getFood () 
          sleep 10
          eat food
          return ()
      }
    

    That said, in practice, I'm not sure I would actually want to use this. I would probably just us a seq { .. } computation that uses yield to accumulat the steps of the plan.