Friday, October 1, 2010

More Novice F# Computation Expression Bind/Return Mechanics

Today’s post is more F# “beginner” stuff I’m doing to help myself learn to think about workflows (or computation expressions as they are also called). As I’ve said before, I’ve gotten to the stage where I can usually puzzle out how to make a workflow do what I need it to do. However, my goal is to internalize the mechanics of workflows to the point where I can proactively recognize situations where they might be useful.

Paradoxically then, here is a particularly useless example. It does little more than simply perform a set of serial conversions. But it does illustrate the Bind/Return calling chain in a way that makes plain the “de-sugaring” mechanics. So I thought I would post it here. (As always, the code and information here are presented "as-is" and without warranty or implied fitness of any kind; use at your own risk.)

type Binder () =
  // Bind:0
  member this.Bind (v:int,f:string->float) =
    // v From Caller
    let down = v.ToString()
    let func = f down // Calls Bind:1
    let up = (float) func
    up // To Caller:
  // Bind:1
  member this.Bind (v:string,f:float->string) =
    // v From Bind:0
    let down = (float) v
    let func = f down // Calls Bind:2
    let up = (float) func
    up // To Bind:0
  // Bind:2
  member this.Bind (v:float,f:byte->double) =
    // v From Bind:1
    let down = (byte) v
    let func = f down // Calls Bind:3
    let up = func.ToString()
    up // To Bind:1
  // Bind:3
  member this.Bind (v:byte,f:byte list->int) =
    // v From Bind:2
    let down = [v;v]
    let func = f down // Calls Return
    let up = (double) func
    up // To Bind:2
  // Return
  member this.Return (v:byte list) = 
    // v From Bind:3
    let up = (int) (List.sum v)
    up // To Bind:3
let f = Binder () {
  let! x = 32 // Bind:0
  let! x =// Bind:1
  let! x =// Bind:2
  let! x =// Bind:3
  return x    // Return
printfn "Your breakpoint here."

No comments: