‘Iacta alea est’
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
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?
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.
Uncaught TypeError: Cannot read property 'expected_property' of null
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.
Maybe this value is
Nothing or maybe it is
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
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.