5 minutes with Computation Expressions in F#

jkone27
3 min readOct 22, 2021

Or banging curly braces { ! }

Some time ago I was trying to understand a bit CEs (Computation Expressions) in F# to see what they can achieve.

First 2 mind-blowing facts for the avg .net dev.

  • F# Has Curls! : If you never programmed in F# before and you were always afraid you had no curly braces, this post will show you that F# does have curls, and why curly braces are way more useful in this language instead of being used for simple expression scoping — which, hey, can be achieved by whitespaces and tabs LOL to not be nasty to the eye, like many langs (e.g. python) already do.
  • The return keyword that you loved is actually still useful!

Now let’s get over this childhood trauma 🧒🏿🥰

WTH { ! } is a Computation Expression?

Here are some examples of ready-to-cook F# CEs:

seq { ... } // IEnumerable<T> computationasync { 
let! x = someAsyncMethod()
return x
}
task {
let! x = someTaskMethod() // TaskBuilder.fs
return x
}
query { ... } // IQueriable<T> computation

While I didn’t master at all the topic in its complete picture, here is a quick gist of it, so don’t be harsh at me.

Open a new .fsx file in vs code, and you should be able to follow easily on these scripts.

Maybe C.E. Builder

type MaybeBuilder() =   member this.Bind(x, f) = // 🔫 the banger! damn     
match x with
| Some(x) -> f(x)
| _ -> None
member this.Delay(f) = f()

member this.Return(x) = Some x
// statically build your computation expression! (Super Power)
// new is omitted as it's not required in F#
let maybe = MaybeBuilder()

And.. Action 🎬

let r = maybe {        
let x = Some 1
let! y = x // 🔫! BANG, get it bab@
return 1 // in a c.e. you wanna use return keyword
} // int option (inferred type)

What does this mean?

Well, it means everything within those curly braces is an option type (a special case of maybe type), so either a Something or Nothing.

Banger!

With the bang! operator, you can retrieve the value to use it in your computations curlies! amazing! The behind-the-scene operator of your C.E. builder is actually the Bind method.

Always make use of the return keyword (mapped by the return operator).

Now that you know this, you can create your own computation expression! start playing around, here is the official reference! have fun.

Diving Further

--

--