Course map
Haskell // 13

Recursion and folds

Read

Recursion

Haskell has no for loop. A function repeats by calling itself on a smaller input until it reaches a base case.

factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)

len :: [a] -> Int
len []       = 0
len (_ : xs) = 1 + len xs

mySum :: [Int] -> Int
mySum []       = 0
mySum (x : xs) = x + mySum xs

Each equation handles one shape: the base case stops, the other case does one step and recurses. len and mySum have exactly the same shape, which is a hint.

01 / 05