Day 1 of Elm
Eke Enyinnaya Diala
Posted on August 3, 2022
Started learning functional programming in Elm yesterday and it has been fun. Tried learning with Lisp and Haskell but didn't make much progress. Decided to go with Elm and it has been easier and better for me.
The most difficult bit about transitioning into Functional Programming is wrapping your head around everything being an expression that evaluates to a result.
Conditionals
Take the concept of conditionals for example. In Javascript land, conditionals are statements but in Elm they are expressions. This means that conditionals in Elm must resolve (evaluate?) to a value and therefore must also have an else
block. In a sense, as Richard Feldman explains, conditionals in elm are better thought about as ternary operators in Javascript. Since the conditional is an expression and must evaluate to a value, it makes sense that the else
block must be defined.
so this block of code in Elm:
pluralise singular plural quantity =
if quantity == 1 then
singular
else
plural
and this in JS are equivalent:
const pluralize = (singular, plural, quantity) => quantity === 1 ? singular : plural;
but not exactly equivalent to this even if they achieve the same result:
const pluralize = (singular, plural, quantity) => {
if (quantity === 1) return singular;
return plural;
};
because in the above code you can omit the else
block and the code will still compile and you will run into runtime exceptions later. Elm massively frowns at runtime exceptions. It does not allow its possibility.
Parentheses
The role of parenthesis in Elm is interesting. Here, I will just quote Richard Feldman:
Parenthesis disambiguate between nested expressions.
This is interesting because in Javascript, parenthesis can be used to disambiguate but they are also used for different other purposes including calling functions, creating functions, conditionals for loops and if statements, etc.
In Elm, it does what it does in Math; disambiguate between nested expressions.
That's all for yesterday. Will write about what I learned in Elm today later.
Posted on August 3, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.