layout: post
title: “Introducing ‘bind’”
description: “Steps towards creating our own ‘let!’ “
nav: thinking-functionally
seriesId: “Computation Expressions”

seriesOrder: 3

In the last post we talked about how we can think of let as a nice syntax for doing continuations behind scenes.
And we introduced a pipeInto function that allowed us to add hooks into the continuation pipeline.

Now we are ready to look at our first builder method, Bind, which formalizes this approach and is the core of any computation expression.

Introducing “Bind “

The MSDN page on computation expressions describes the let! expression as syntactic sugar for a Bind method. Let’s look at this again:

Here’s the let! expression documentation, along with a real example:

  1. // documentation
  2. {| let! pattern = expr in cexpr |}
  3. // real example
  4. let! x = 43 in some expression

And here’s the Bind method documentation, along with a real example:

  1. // documentation
  2. builder.Bind(expr, (fun pattern -> {| cexpr |}))
  3. // real example
  4. builder.Bind(43, (fun x -> some expression))

Notice a few interesting things about this:

  • Bind takes two parameters, an expression (43) and a lambda.
  • The parameter of the lambda (x) is bound to the expression passed in as the first parameter. (In this case at least. More on this later.)
  • The parameters of Bind are reversed from the order they are in let!.

So in other words, if we chain a number of let! expressions together like this:

  1. let! x = 1
  2. let! y = 2
  3. let! z = x + y

the compiler converts it to calls to Bind, like this:

  1. Bind(1, fun x ->
  2. Bind(2, fun y ->
  3. Bind(x + y, fun z ->
  4. etc

I think you can see where we are going with this by now.

Indeed, our pipeInto function is exactly the same as the Bind method.

This is a key insight: computation expressions are just a way to create nice syntax for something that we could do ourselves.

A standalone bind function

Having a “bind” function like this is actually a standard functional pattern, and it is not dependent on computation expressions at all.

First, why is it called “bind”? Well, as we’ve seen, a “bind” function or method can be thought of as feeding an input value to a function. This is known as “binding“ a value to the parameter of the function (recall that all functions have only one parameter).

So when you think of bind this this way, you can see that it is similar to piping or composition.

In fact, you can turn it into an infix operation like this:

  1. let (>>=) m f = pipeInto(m,f)

By the way, this symbol “>>=” is the standard way of writing bind as an infix operator. If you ever see it used in other F# code, that is probably what it represents.

Going back to the safe divide example, we can now write the workflow on one line, like this:

  1. let divideByWorkflow x y w z =
  2. x |> divideBy y >>= divideBy w >>= divideBy z

You might be wondering exactly how this is different from normal piping or composition? It’s not immediately obvious.

The answer is twofold:

  • First, the bind function has extra customized behavior for each situation. It is not a generic function, like pipe or composition.

  • Second, the input type of the value parameter (m above) is not necessarily the same as the output type of the function parameter (f above), and so one of the things that bind does is handle this mismatch elegantly so that functions can be chained.

As we will see in the next post, bind generally works with some “wrapper” type. The value parameter might be of WrapperType<TypeA>, and then the signature of the function parameter of bind function is always TypeA -> WrapperType<TypeB>.

In the particular case of the bind for safe divide, the wrapper type is Option. The type of the value parameter (m above) is Option<int> and the signature of the function parameter (f above) is int -> Option<int>.

To see bind used in a different context, here is an example of the logging workflow expressed using a infix bind function:

  1. let (>>=) m f =
  2. printfn "expression is %A" m
  3. f m
  4. let loggingWorkflow =
  5. 1 >>= (+) 2 >>= (*) 42 >>= id

In this case, there is no wrapper type. Everything is an int. But even so, bind has the special behavior that performs the logging behind the scenes.

Option.bind and the “maybe” workflow revisited

In the F# libraries, you will see Bind functions or methods in many places. Now you know what they are for!

A particularly useful one is Option.bind, which does exactly what we wrote by hand above, namely

  • If the input parameter is None, then don’t call the continuation function.
  • If the input parameter is Some, then do call the continuation function, passing in the contents of the Some.

Here was our hand-crafted function:

  1. let pipeInto (m,f) =
  2. match m with
  3. | None ->
  4. None
  5. | Some x ->
  6. x |> f

And here is the implementation of Option.bind:

  1. module Option =
  2. let bind f m =
  3. match m with
  4. | None ->
  5. None
  6. | Some x ->
  7. x |> f

There is a moral in this — don’t be too hasty to write your own functions. There may well be library functions that you can reuse.

Here is the “maybe” workflow, rewritten to use Option.bind:

  1. type MaybeBuilder() =
  2. member this.Bind(m, f) = Option.bind f m
  3. member this.Return(x) = Some x

Reviewing the different approaches so far

We’ve used four different approaches for the “safe divide” example so far. Let’s put them together side by side and compare them once more.

Note: I have renamed the original pipeInto function to bind, and used Option.bind instead of our original custom implementation.

First the original version, using an explicit workflow:

  1. module DivideByExplicit =
  2. let divideBy bottom top =
  3. if bottom = 0
  4. then None
  5. else Some(top/bottom)
  6. let divideByWorkflow x y w z =
  7. let a = x |> divideBy y
  8. match a with
  9. | None -> None // give up
  10. | Some a' -> // keep going
  11. let b = a' |> divideBy w
  12. match b with
  13. | None -> None // give up
  14. | Some b' -> // keep going
  15. let c = b' |> divideBy z
  16. match c with
  17. | None -> None // give up
  18. | Some c' -> // keep going
  19. //return
  20. Some c'
  21. // test
  22. let good = divideByWorkflow 12 3 2 1
  23. let bad = divideByWorkflow 12 3 0 1

Next, using our own version of “bind” (a.k.a. “pipeInto”)

  1. module DivideByWithBindFunction =
  2. let divideBy bottom top =
  3. if bottom = 0
  4. then None
  5. else Some(top/bottom)
  6. let bind (m,f) =
  7. Option.bind f m
  8. let return' x = Some x
  9. let divideByWorkflow x y w z =
  10. bind (x |> divideBy y, fun a ->
  11. bind (a |> divideBy w, fun b ->
  12. bind (b |> divideBy z, fun c ->
  13. return' c
  14. )))
  15. // test
  16. let good = divideByWorkflow 12 3 2 1
  17. let bad = divideByWorkflow 12 3 0 1

Next, using a computation expression:

  1. module DivideByWithCompExpr =
  2. let divideBy bottom top =
  3. if bottom = 0
  4. then None
  5. else Some(top/bottom)
  6. type MaybeBuilder() =
  7. member this.Bind(m, f) = Option.bind f m
  8. member this.Return(x) = Some x
  9. let maybe = new MaybeBuilder()
  10. let divideByWorkflow x y w z =
  11. maybe
  12. {
  13. let! a = x |> divideBy y
  14. let! b = a |> divideBy w
  15. let! c = b |> divideBy z
  16. return c
  17. }
  18. // test
  19. let good = divideByWorkflow 12 3 2 1
  20. let bad = divideByWorkflow 12 3 0 1

And finally, using bind as an infix operation:

  1. module DivideByWithBindOperator =
  2. let divideBy bottom top =
  3. if bottom = 0
  4. then None
  5. else Some(top/bottom)
  6. let (>>=) m f = Option.bind f m
  7. let divideByWorkflow x y w z =
  8. x |> divideBy y
  9. >>= divideBy w
  10. >>= divideBy z
  11. // test
  12. let good = divideByWorkflow 12 3 2 1
  13. let bad = divideByWorkflow 12 3 0 1

Bind functions turn out to be very powerful. In the next post we’ll see that combining bind with wrapper types creates an elegant way of passing extra information around in the background.

Exercise: How well do you understand?

Before you move on to the next post, why don’t you test yourself to see if you have understood everything so far?

Here is a little exercise for you.

Part 1 - create a workflow

First, create a function that parses a string into a int:

  1. let strToInt str = ???

and then create your own computation expression builder class so that you can use it in a workflow, as shown below.

  1. let stringAddWorkflow x y z =
  2. yourWorkflow
  3. {
  4. let! a = strToInt x
  5. let! b = strToInt y
  6. let! c = strToInt z
  7. return a + b + c
  8. }
  9. // test
  10. let good = stringAddWorkflow "12" "3" "2"
  11. let bad = stringAddWorkflow "12" "xyz" "2"

Part 2 — create a bind function

Once you have the first part working, extend the idea by adding two more functions:

  1. let strAdd str i = ???
  2. let (>>=) m f = ???

And then with these functions, you should be able to write code like this:

  1. let good = strToInt "1" >>= strAdd "2" >>= strAdd "3"
  2. let bad = strToInt "1" >>= strAdd "xyz" >>= strAdd "3"

Summary

Here’s a summary of the points covered in this post:

  • Computation expressions provide a nice syntax for continuation passing, hiding the chaining logic for us.
  • bind is the key function that links the output of one step to the input of the next step.
  • The symbol >>= is the standard way of writing bind as an infix operator.