Expressions

Expressions

if .. then .. else

-- Every `then` must have a corresponding `else`
abs x = if x > 0 then x else -x

-- Indentations
sign x =
  if x > 0
    then print "pos"
    else if x < 0
      then print "neg"
      else print "zero"

case .. of

rgb = Red

f = case rgb of
      Red   -> "red"
      Green -> "green"
      Blue  -> "blue"
-- f has value "red"

g = case rgb of Green -> "red"; _ -> "not red"
-- g has value "not red"

List comprehensions

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

-- examples
[x*2 | x <- [1,2,3]]   -- [2,4,6]

[x * x | x <- [1..10]] -- [1,4,9,16,25,36,49,64,81,100]

-- multiple generators
[(x,y) | x <- [1,2,3], y <- [4,5]]

-- dependent generators
[(x,y) | x <- [1..3], y <- [x..3]]

-- conditions
even i = 0 == i % 2
[x | x <- [1..10], even x]

Enumerations, Range

[1..10]
--[1,2,3,4,5,6,7,8,9,10]

[0, 5..100]
-- [0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100]

['a'..'z']
--"abcdefghijklmnopqrstuvwxyz"