Expressions

if .. then .. else

  1. -- Every `then` must have a corresponding `else`
  2. abs x = if x > 0 then x else -x
  3. -- Indentations
  4. sign x =
  5. if x > 0
  6. then print "pos"
  7. else if x < 0
  8. then print "neg"
  9. else print "zero"

case .. of

  1. rgb = Red
  2. f = case rgb of
  3. Red -> "red"
  4. Green -> "green"
  5. Blue -> "blue"
  6. -- f has value "red"
  7. g = case rgb of Green -> "red"; _ -> "not red"
  8. -- g has value "not red"

List comprehensions

A list comprehension consists of four types of elements: generators, guards, local bindings, and targets.

  1. -- examples
  2. [x*2 | x <- [1,2,3]] -- [2,4,6]
  3. [x * x | x <- [1..10]] -- [1,4,9,16,25,36,49,64,81,100]
  4. -- multiple generators
  5. [(x,y) | x <- [1,2,3], y <- [4,5]]
  6. -- dependent generators
  7. [(x,y) | x <- [1..3], y <- [x..3]]
  8. -- conditions
  9. even i = 0 == i % 2
  10. [x | x <- [1..10], even x]

Enumerations, Range

  1. [1..10]
  2. --[1,2,3,4,5,6,7,8,9,10]
  3. [0, 5..100]
  4. -- [0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100]
  5. ['a'..'z']
  6. --"abcdefghijklmnopqrstuvwxyz"