Imperative computation in F# (II.) - Writing break and continue

As I already wrote in the first part of this series, the F# language doesn't support some of the language constructs known from imperative languages such as C#. In particular, we cannot use imperative return statement that returns the result of a function from any place in the function code. In functional languages, every construct is an expression, so to get the overall result of the function, the F# language evaluates the expression and the value of the expression is used as the result. In the previous article, we've seen that we can simulate this construct in the F# language using F# computation expressions and I showed how to implement computation named imperative that allows us to write for example the exists function for working with sequences like this:

let exists f inp = imperative {
  for v in inp do 
    if f(v) then return true
  return false }

In this article, we're going to look at two more imperative constructs and we're going to talk about break and continue. We'll see that we can quite easily extend the computation builder from the previous article to allow writing code that is syntactically very close to what you would write in C#. As I already mentioned, there are of course some performance overheads when using computation expressions, but I find it very interesting how nice imperative syntax we can get in functional F#:

imperative { 
  for x in 1 .. 10 do 
    if (x % 3 = 0) then do! continue
    printfn "number = %d" x }

The only difference between this code and the code we'd probably write if F# supported continue as a keyword is that we need to wrap the code inside the imperative computation and that we need to add the do! primitive before the continue value. Now that we've seen an example of using the continue value inside the imperative computations, let's look how we can extend the computation builder from the previous article to add this feature...

Published: Saturday, 25 April 2009, 4:31 PM
Tags: functional, f#
Read the complete article

All blog posts by tag

f# (112), functional (66), research (48), c# (37), asynchronous (27), academic (26), parallel (23), programming languages (21), functional programming (20), universe (20), meta-programming (18), philosophy (16), links (15), presentations (14), data science (12), writing (12), joinads (12), web (11), thegamma (11), talks (9), data journalism (9), math and numerics (9), random thoughts (9), phalanger (8), haskell (7), mono (7), webcast (7), design (5), fslab (5), open source (5), architecture (4), visualization (4), fun (4), accelerator (4), type providers (3), linq (3), f# data (3), .net (3), training (2), coeffects (2), deedle (2), monads (2), art (2), fractals (2), funscript (2), new york (2), manning (2), books (2)