Elm

Typed Functional Programming For The Web

Why Choose Elm?

Purity

x → y

Immutability

x = x + 1

Designed For Frontend

Tooling

  • Elm REPL
  • Elm Make
  • Elm Package Manager
  • Elm Reactor

Elm Syntax

Crash Course

Functions


add x y = x + y

add 10 11 -- 21

add' = (\x y -> x + y) -- anonymous function
            

Pattern Matching


or b1 b2 =
  case b1 of
    True -> True
    False -> b2
            
Let...In

f x =
  let
    double = x * 2
  in
    double + double
            

Lists


xs = [1, 2, 3]

4::xs -- [4, 1, 2, 3]

head xs
  case xs of
    x::xs -> Just x
    []    -> Nothing
            

Tuples


t = (1, "Foo")
t' = (2, "Bar", [1, 2, 3])
            

Union Types


type Action =
  Add
| Sub
            

calc action n m =
  case action of
    Add -> n + m
    Sub -> n - m

calc Add 1 2 -- 3

calc Sub 5 3 -- 2
            

Union Types

With Values

type Action =
  Increment
| Decrement

type Counter = Counter Int
            


step action (Counter n)=
  case action of
    Increment -> Counter (n + 1)
    Decrement -> Counter (n - 1)

step Increment (Counter 1) -- Counter 2

step Decrement (Counter 2) -- Counter 1
            

Polymorphic Unions


type Maybe a =
  Just a
| Nothing

type Either a b =
  Left a
| Right b
            

Records

Defining & Accessing

person = { first = "Jane", last = "Smith" }

person.first -- "Jane"

.last person -- "Smith"

List.map .last people -- a list of last names

sayHi { first } =
  "Hi " ++ first

sayHi person -- "Hi Jane"
            

Records

Updating

{ person - first } -- removes a field

{ person | age = 20 } -- adds a new field & value

{ person | first <- "John" } -- updates a field

{ person - last | surname = "Smith" }
-- combine adding & deleting to rename a field
            

Types

The Part Where Everyone Stops Listening

Examples of Types


5 : number

4.5 : Float

"Hi" : String

'c' : Char

Keyboard.presses : Signal Int

person : {first : String, last : String}

add : Int -> Int -> Int

map : (a -> b) -> List a -> List b
            

Demo

Further

Thanks!

@thunk_life
https://thunklife.github.io/elm-talk