Elm is a functional programming language for building front-end web applications
function =
let
xs = [1,2,3]
in sum (map (\x -> x + 1) xs)
function():
xs = [1,2,3]
result = 0
for x in xs:
x = x + 1
result = result + x
return result
In Elm, function application is denoted using space, ex:
function var1 var2
Moreover function application is assumed to have higher priority than all other operators, ex:
sin 0+2 = (sin 0) + 2
Mathematics | Elm |
\(f(x)\) | \(f \quad x\) |
\(f(x,y)\) | \(f \quad x \quad y\) |
\(f(g(x))\) | \(f \quad (g \quad x)\) |
\(f(x,g(y))\) | \(f \quad x \quad (g \quad y)\) |
\(f(x)g(y)\) | \(f \quad x \quad * \quad g \quad y\) |
Elm has core libraries (i.e predefined functions) that are fequently used
Reverse a list
List.reverse [1,2,3,4]
Find the length of a list
List.length [1,2,3,4]
Sum the elements of a list (of numbers)
List.sum [1,1,1]
Take n elements from a list
List.take 2 [1,2,3,4]
Remove n elements from a list
List.drop 2 [1,2,3,4]
Retrieve the first element of a list
List.head [1,2,3,4]
Remove the first element from a list
List.tail [1,2,3,4]
Replace a Maybe value with a default value
Maybe.withDefault 0 (List.head [])
Chain two functions together
Maybe.andThen List.head (List.tail [1,2,3])
The pipe operator can be used as an alternative to brackets
List.tail [1,2,3]
|> Maybe.andThen List.head
You can create and reuse your own functions
index0 xs n = Maybe.withDefault 0 (List.head (List.drop n xs))
Syntax states the rules for forming valid expressions
Function and argument (variable) names must begin with a lower-case letter. For example:
myFun fun1 arg_2 x'
By convention, lists usually have an s suffix on their name. For example :
xs ns nss
Consider the following code
poly x = (x+1) * (x+1)
To reuse the computation \((x+1)\) we can define a local variable
poly x = let y = x+1
in y * y
Please note, let and where expressions are EXPRESSIONS NOT STATEMENTS
Definition 1 Definition 2
f = let x = 5 f = let z = y + x
y = x + 6 x = 5
z = y + x y = x + 6
in z in z
-- Definitions Are Equivalent