Chapter 2. Reading Elm

It’s a little hard to talk too much about Elm without showing some code. This report isn’t meant to be a comprehensive guide, but merely to give you a feel for what the language looks like and how it works. So, let’s see what some Elm code looks like! (I will warn you that if you’re not familiar with this sort of programming, the code presented in this chapter may feel a little weird. I encourage you to squint your eyes and persevere.)

Here’s a basic function called mathPlease that takes two numbers, x and y, and does some math with them:

mathPlease x y = (x + y) * 5

Elm is an expression-oriented language. There’s no return statement because each expression will naturally result in a value. This may become a bit clearer when we do something familiar like write an if expression. Here’s a function called aboveTen that takes a number, x, and returns True if it’s above 10:

aboveTen x =
    if x > 10 then
       True
    else
       False

Also note that this function can only result in one type of thing. In this case it results in a Bool, which can be either True or False. We couldn’t have one branch that returns a String, while another branch returns True. In order to capture more complex results, we’d have to define a new type, which we’ll get to shortly.

Because Elm is based on expressions, we don’t have the list of instructions that is the hallmark of imperative languages. If we need some workspace to make a more complicated function, Elm has a let...in construct, which you ...

Get Why Elm? now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.