Early returns can be useful in statement-based languages like Java or C# to restructure code and eliminate nesting.

When using F# for the first time, one of the things I struggled with was the lack of early returns. The concept of an early return doesn’t make sense in an expression-based language, where we’re composing values together to produce new values rather than sequencing statements. How then do we deal with nesting in F#?

Classic Solution: Bind and Computation Expressions

Here’s some code that looks two things up, then combines those things if they both have a value:

One level of nesting is not awful, but…


Static types can really aid in designing software, especially if your type system has good facilities for composing those types.

A case study

Let’s say we want to define a binary tree. Each node in a binary tree consists of an element and 0–2 children. Here’s how we could define a tree of integers in Haskell:

data Tree = Empty
| Node Tree Int Tree

This syntax may not be familiar, so let’s break it down. We are defining a custom data type called Tree. The | (read “or”) indicates that there are two variants. …

Justin Hewlett

Software Developer at @pluralsight. Especially interested in functional programming and programming languages. Find me on twitter @justin_hewlett

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store