layout: post
title: “Implementing a builder: The rest of the standard methods”
description: “Implementing While, Using, and exception handling”
nav: thinking-functionally
seriesId: “Computation Expressions”

seriesOrder: 11

We’re coming into the home stretch now. There are only a few more builder methods that need to be covered, and then you will be ready to tackle anything!

These methods are:

  • While for repetition.
  • TryWith and TryFinally for handling exceptions.
  • Use for managing disposables

Remember, as always, that not all methods need to be implemented. If While is not relevant to you, don’t bother with it.

One important note before we get started: all the methods discussed here rely on delays being used. If you are not using delay functions, then none of the methods will give the expected results.

Implementing “While”

We all know what “while” means in normal code, but what does it mean in the context of a computation expression?
To understand, we have to revisit the concept of continuations again.

In previous posts, we saw that a series of expressions is converted into a chain of continuations like this:

  1. Bind(1,fun x ->
  2. Bind(2,fun y ->
  3. Bind(x + y,fun z ->
  4. Return(z) // or Yield

And this is the key to understanding a “while” loop — it can be expanded in the same way.

First, some terminology. A while loop has two parts:

  • There is a test at the top of the “while” loop which is evaluated each time to determine whether the body should be run. When it evaluates to false, the while loop is “exited”. In computation expressions, the test part is known as the “guard”.
    The test function has no parameters, and returns a bool, so its signature is unit -> bool, of course.
  • And there is the body of the “while” loop, evaluated each time until the “while” test fails. In computation expressions, this is a delay function that evaluates to a wrapped value. Since the body of the while loop is always the same, the same function is evaluated each time.
    The body function has no parameters, and returns nothing, and so its signature is just unit -> wrapped unit.

With this in place, we can create pseudo-code for a while loop using continuations:

  1. // evaluate test function
  2. let bool = guard()
  3. if not bool
  4. then
  5. // exit loop
  6. return what??
  7. else
  8. // evaluate the body function
  9. body()
  10. // back to the top of the while loop
  11. // evaluate test function again
  12. let bool' = guard()
  13. if not bool'
  14. then
  15. // exit loop
  16. return what??
  17. else
  18. // evaluate the body function again
  19. body()
  20. // back to the top of the while loop
  21. // evaluate test function a third time
  22. let bool'' = guard()
  23. if not bool''
  24. then
  25. // exit loop
  26. return what??
  27. else
  28. // evaluate the body function a third time
  29. body()
  30. // etc

One question that is immediately apparent is: what should be returned when the while loop test fails? Well, we have seen this before with if..then.., and the answer is of course to use the Zero value.

The next thing is that the body() result is being discarded. Yes, it is a unit function, so there is no value to return, but even so, in our expressions, we want to be able to hook into this so we can add behavior behind the scenes. And of course, this calls for using the Bind function.

So here is a revised version of the pseudo-code, using Zero and Bind:

  1. // evaluate test function
  2. let bool = guard()
  3. if not bool
  4. then
  5. // exit loop
  6. return Zero
  7. else
  8. // evaluate the body function
  9. Bind( body(), fun () ->
  10. // evaluate test function again
  11. let bool' = guard()
  12. if not bool'
  13. then
  14. // exit loop
  15. return Zero
  16. else
  17. // evaluate the body function again
  18. Bind( body(), fun () ->
  19. // evaluate test function a third time
  20. let bool'' = guard()
  21. if not bool''
  22. then
  23. // exit loop
  24. return Zero
  25. else
  26. // evaluate the body function again
  27. Bind( body(), fun () ->
  28. // etc

In this case, the continuation function passed into Bind has a unit parameter, because the body function does not have a value.

Finally, the pseudo-code can be simplified by collapsing it into a recursive function like this:

  1. member this.While(guard, body) =
  2. // evaluate test function
  3. if not (guard())
  4. then
  5. // exit loop
  6. this.Zero()
  7. else
  8. // evaluate the body function
  9. this.Bind( body(), fun () ->
  10. // call recursively
  11. this.While(guard, body))

And indeed, this is the standard “boiler-plate” implementation for While in almost all builder classes.

It is a subtle but important point that the value of Zero must be chosen properly. In previous posts, we saw that we could set the value for Zero to be None or Some () depending on the workflow. For While to work however, the Zero must be set to Some () and not None, because passing None into Bind will cause the whole thing to aborted early.

Also note that, although this is a recursive function, we didn’t need the rec keyword. It is only needed for standalone functions that are recursive, not methods.

“While” in use

Let’s look at it being used in the trace builder. Here’s the complete builder class, with the While method:

  1. type TraceBuilder() =
  2. member this.Bind(m, f) =
  3. match m with
  4. | None ->
  5. printfn "Binding with None. Exiting."
  6. | Some a ->
  7. printfn "Binding with Some(%A). Continuing" a
  8. Option.bind f m
  9. member this.Return(x) =
  10. Some x
  11. member this.ReturnFrom(x) =
  12. x
  13. member this.Zero() =
  14. printfn "Zero"
  15. this.Return ()
  16. member this.Delay(f) =
  17. printfn "Delay"
  18. f
  19. member this.Run(f) =
  20. f()
  21. member this.While(guard, body) =
  22. printfn "While: test"
  23. if not (guard())
  24. then
  25. printfn "While: zero"
  26. this.Zero()
  27. else
  28. printfn "While: body"
  29. this.Bind( body(), fun () ->
  30. this.While(guard, body))
  31. // make an instance of the workflow
  32. let trace = new TraceBuilder()

If you look at the signature for While, you will see that the body parameter is unit -> unit option, that is, a delayed function. As noted above, if you don’t implement Delay properly, you will get unexpected behavior and cryptic compiler errors.

  1. type TraceBuilder =
  2. // other members
  3. member
  4. While : guard:(unit -> bool) * body:(unit -> unit option) -> unit option

And here is a simple loop using a mutable value that is incremented each time round.

  1. let mutable i = 1
  2. let test() = i < 5
  3. let inc() = i <- i + 1
  4. let m = trace {
  5. while test() do
  6. printfn "i is %i" i
  7. inc()
  8. }

Handling exceptions with “try..with”

Exception handling is implemented in a similar way.

If we look at a try..with expression for example, it has two parts:

  • There is the body of the “try”, evaluated once. In a computation expressions, this will be a delayed function that evaluates to a wrapped value. The body function has no parameters, and so its signature is just unit -> wrapped type.
  • The “with” part handles the exception. It has an exception as a parameters, and returns the same type as the “try” part, so its signature is exception -> wrapped type.

With this in place, we can create pseudo-code for the exception handler:

  1. try
  2. let wrapped = delayedBody()
  3. wrapped // return a wrapped value
  4. with
  5. | e -> handlerPart e

And this maps exactly to a standard implementation:

  1. member this.TryWith(body, handler) =
  2. try
  3. printfn "TryWith Body"
  4. this.ReturnFrom(body())
  5. with
  6. e ->
  7. printfn "TryWith Exception handling"
  8. handler e

As you can see, it is common to use pass the returned value through ReturnFrom so that it gets the same treatment as other wrapped values.

Here is an example snippet to test how the handling works:

  1. trace {
  2. try
  3. failwith "bang"
  4. with
  5. | e -> printfn "Exception! %s" e.Message
  6. } |> printfn "Result %A"

Implementing “try..finally”

try..finally is very similar to try..with.

  • There is the body of the “try”, evaluated once. The body function has no parameters, and so its signature is unit -> wrapped type.
  • The “finally” part is always called. It has no parameters, and returns a unit, so its signature is unit -> unit.

Just as with try..with, the standard implementation is obvious.

  1. member this.TryFinally(body, compensation) =
  2. try
  3. printfn "TryFinally Body"
  4. this.ReturnFrom(body())
  5. finally
  6. printfn "TryFinally compensation"
  7. compensation()

Another little snippet:

  1. trace {
  2. try
  3. failwith "bang"
  4. finally
  5. printfn "ok"
  6. } |> printfn "Result %A"

Implementing “using”

The final method to implement is Using. This is the builder method for implementing the use! keyword.

This is what the MSDN documentation says about use!:

  1. {| use! value = expr in cexpr |}

is translated to:

  1. builder.Bind(expr, (fun value -> builder.Using(value, (fun value -> {| cexpr |} ))))

In other words, the use! keyword triggers both a Bind and a Using. First a Bind is done to unpack the wrapped value,
and then the unwrapped disposable is passed into Using to ensure disposal, with the continuation function as the second parameter.

Implementing this is straightforward. Similar to the other methods, we have a body, or continuation part, of the “using” expression, which is evaluated once. This body function has a “disposable” parameter, and so its signature is #IDisposable -> wrapped type.

Of course we want to ensure that the disposable value is always disposed no matter what, so we need to wrap the call to the body function in a TryFinally.

Here’s a standard implementation:

  1. member this.Using(disposable:#System.IDisposable, body) =
  2. let body' = fun () -> body disposable
  3. this.TryFinally(body', fun () ->
  4. match disposable with
  5. | null -> ()
  6. | disp -> disp.Dispose())

Notes:

  • The parameter to TryFinally is a unit -> wrapped, with a unit as the first parameter, so we created a delayed version of the body that is passed in.
  • Disposable is a class, so it could be null, and we have to handle that case specially. Otherwise we just dispose it in the “finally” continuation.

Here’s a demonstration of Using in action. Note that the makeResource makes a wrapped disposable. If it wasn’t wrapped, we wouldn’t need the special
use! and could just use a normal use instead.

  1. let makeResource name =
  2. Some {
  3. new System.IDisposable with
  4. member this.Dispose() = printfn "Disposing %s" name
  5. }
  6. trace {
  7. use! x = makeResource "hello"
  8. printfn "Disposable in use"
  9. return 1
  10. } |> printfn "Result: %A"

“For” revisited

Finally, we can revisit how For is implemented. In the previous examples, For took a simple list parameter. But with Using and While under our belts, we can change it to accept any IEnumerable<_> or sequence.

Here’s the standard implementation for For now:

  1. member this.For(sequence:seq<_>, body) =
  2. this.Using(sequence.GetEnumerator(),fun enum ->
  3. this.While(enum.MoveNext,
  4. this.Delay(fun () -> body enum.Current)))
  5. {% endhighlight fsharp %}
  6. As you can see, it is quite different from the previous implementation, in order to handle a generic `IEnumerable<_>`.
  7. * We explicitly iterate using an `IEnumerator<_>`.
  8. * `IEnumerator<_>` implements `IDisposable`, so we wrap the enumerator in a `Using`.
  9. * We use `While .. MoveNext` to iterate.
  10. * Next, we pass the `enum.Current` into the body function
  11. * Finally, we delay the call to the body function using `Delay`
  12. ## Complete code without tracing
  13. Up to now, all the builder methods have been made more complex than necessary by the adding of tracing and printing expressions. The tracing is helpful to understand what is going on,
  14. but it can obscure the simplicity of the methods.
  15. So as a final step, let's have a look at the complete code for the "trace" builder class, but this time without any extraneous code at all. Even though the code is cryptic, the purpose and implementation of each method should now be familiar to you.
  16. ```fsharp
  17. type TraceBuilder() =
  18. member this.Bind(m, f) =
  19. Option.bind f m
  20. member this.Return(x) = Some x
  21. member this.ReturnFrom(x) = x
  22. member this.Yield(x) = Some x
  23. member this.YieldFrom(x) = x
  24. member this.Zero() = this.Return ()
  25. member this.Delay(f) = f
  26. member this.Run(f) = f()
  27. member this.While(guard, body) =
  28. if not (guard())
  29. then this.Zero()
  30. else this.Bind( body(), fun () ->
  31. this.While(guard, body))
  32. member this.TryWith(body, handler) =
  33. try this.ReturnFrom(body())
  34. with e -> handler e
  35. member this.TryFinally(body, compensation) =
  36. try this.ReturnFrom(body())
  37. finally compensation()
  38. member this.Using(disposable:#System.IDisposable, body) =
  39. let body' = fun () -> body disposable
  40. this.TryFinally(body', fun () ->
  41. match disposable with
  42. | null -> ()
  43. | disp -> disp.Dispose())
  44. member this.For(sequence:seq<_>, body) =
  45. this.Using(sequence.GetEnumerator(),fun enum ->
  46. this.While(enum.MoveNext,
  47. this.Delay(fun () -> body enum.Current)))

After all this discussion, the code seems quite tiny now. And yet this builder implements every standard method, uses delayed functions.
A lot of functionality in a just a few lines!