Essay - Published: 2024.01.31 | create | fsharp | tech |
DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)
F# is a beautiful language. But a lot of its code looks a little weird - it achieves its beauty by being very particular about the paradigms it supports, often discarding patterns used by mainstream languages that have revealed themselves to be negatives rather than positives.
This can make picking up F# hard.
One of the biggest struggles I had when I got into F# was how to write early returns. Early returns are a common way to make code cleaner in mainstream languages by hoisting invalid conditions to the top of a function, reducing the nesting complexity in the body. But F# is a bit more functional than that and tends to bias towards more expressive techniques like Monads.
But Monads are confusing and I think early returns are still a reasonable pattern in F# so here I'll show you how to do them.
We can achieve early returns in F# by relying on the if/then/else conditionals.
By filling out the then with the early return value you'd like, you can achieve early returns without Monads.
Here's some code:
let earlyReturn
(shouldEarly : bool)
: bool
=
if shouldEarly
then
printfn "Early returning!"
true
else
printfn "Not early returning!"
false
This code:
Note that you can chain multiple of these together. In this example we do the same thing but chain two potential early returns with the if/then/else approach.
let earlyReturn2
(shouldEarly1 : bool)
(shouldEarly2 : bool)
: bool * bool
=
if shouldEarly1
then
printfn "Early return 1"
(true, false)
else
if shouldEarly2
then
printfn "Early return 2"
(false, true)
else
printfn "No early return"
(false, false)
You can run this code yourself with the FsharpEarlyReturns Replit.
F# is my favorite language but there is a bit of a learning curve to relearn some patterns of doing things. Long-term simple Monads often lend better to composable railroad systems but leaning on if/then/else is a viable option.
If you liked this post you might also like:
The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.