Functions

A function is a mapping from values of one type to values of another type.

Function Definition and Application

  1. add :: Integer -> Integer -> Integer
  2. add x y = x + y
  3. add 1 2

Polymorphic Functions

  1. length :: forall a. [a] -> Integer
  2. -- example
  3. nats25 :: [Integer]
  4. nats25 = [0..25]
  5. letters :: [Char]
  6. letters = ['a'..'z']
  7. n1 = length nats25 -- 26
  8. n2 = length letters -- 26
  9. zip :: forall a b. [a] -> [b] -> [(a,b)]
  10. ordL = zip nats letters
  11. -- [(0,'a'),(1,'b'),(2,'c'),(3,'d'),(4,'e'),(5,'f'),(6,'g'),(7,'h'),(8,'i'),(9,'j'),(10,'k'),(11,'l'),(12,'m'),(13,'n'),(14,'o'),(15,'p'),(16,'q'),(17,'r'),(18,'s'),(19,'t'),(20,'u'),(21,'v'),(22,'w'),(23,'x'),(24,'y'),(25,'z')]

Currying

  1. -- uncurried
  2. plus :: (Integer, Integer) -> Integer
  3. plus (x, y) = x + y
  4. -- sum is the curried version of plus
  5. sum :: Integer -> Integer -> Integer
  6. sum x y = x + y

Partial application

  1. sum 1 2 :: Integer
  2. sum 1 (2 + 3) :: Integer
  3. add2 = sum 2 :: Integer -> Integer -- partially applied
  4. x = add2 3 :: Integer -- x = 5

High-Order Functions

  1. apply :: forall a b. (a -> b) -> a -> b
  2. apply f x = f x

Recursive Function

  1. fact n = if n == 0 then 1 else n * fact (n - 1)
  2. length [] = 0
  3. length [x|xs] = length xs + 1

Lambda (Anonymous Function)

  1. multBy :: Integer -> Integer -> Integer
  2. multBy n = \m -> m * n
  3. mean :: Integer -> Integer -> Integer
  4. mean = \x y -> (x + y) `div` 2 -- f = (\x -> \y -> (x + y) `div` 2)

Function Pattern Matching

  1. (x, y) = (1, 2)
  2. -- function declartion via pattern matching
  3. allEmpty [] = True
  4. allEmpty _ = False
  5. -- pattern matching stops when it finds the first match

Guarded Equations

  1. abs n | n > 0 = n
  2. | otherwise = -n