‘Iacta alea est’

Maybe Elm

Penned around January 23rd 2016.

One of the strange things that you come across for the first time in Elm if you are not familiar with the functional style is the Maybe type.

All of a sudden your programming language has adopted an air of mystique and starts playing hard to get.

Me: Have you got that value for me Elm?

Elm: Maybe.

Me: What’s the argument to that function?

Elm: Oh, I don’t know, maybe it’s just something or it could be nothing. Look, why don’t you stop all these questions and just let me handle things, okay?

Me: Um, okay then, but what are you up to?

Don’t worry, Elm is being secretive for a reason.

BOOM!

Uncaught TypeError: Cannot read property 'expected_property' of null

BOOM!

Undefined method 'expected.property' for nil:NilClass

The reason Elm is operating with a Maybe is to prevent your application blowing up in your face.

These error messages in JavaScript and Ruby are no doubt buried deep within the stack trace of your application. The concept of null or nil is a problem because you don’t know quite when it might rear its ugly head. You could raise an exception or use the null object pattern but a better way to handle it in a language that supports it is to make the presence of something explicitly optional; either there is something or nothing. We are making explicit to our program (and to ourselves) that the value we are passing around might not exist. Maybe. Maybe this value is Nothing or maybe it is Just something.

Lifting this optionality up to the status of first-class citizen allows us to pass this value around safely and helps us to deal with the ambiguity only when we need to. We can pass around this value (or lack of value) in our program without the slightest bit of worry that it will come back to bite us. It is a little strange to get used to at first, but when you realise what it is doing for you then you breathe a sigh of relief.

We can finally lay our defensive programming approaches to rest; no more checking for null and undefined, the type checker now has an explicit type for dealing with this ambiguity and won’t let you make the same mistakes.

It provides a distinction between some value (Just a) and no value (Nothing) which can be regarded as a typed version of the C convention of returning a null pointer to indicate no value. It is a representation of values that may or may not exist:

type Maybe a
    = Just a
    | Nothing

It’s quite simple when expressed like this and I have no desire to complicate it.

Monday 1st February 2021.