Theory
Recursion and pattern matching is Haskellโs control structure.
Structural Recursion
Break a value into constructors, solve subโparts, reโcombine.
length [] = 0
length (_:xs) = 1 + length xsMutual Recursion
even', odd' :: Int -> Bool
even' 0 = True
even' n = odd' (n-1)
odd' 0 = False
odd' n = even' (n-1)Tail Recursion
Carry accumulator so last action is the recursive call.
sumTR xs = go 0 xs
where
go acc [] = acc
go acc (y:ys) = go (acc + y) ysImplementation
-- literals
0 -> base case
-- constructor patterns
(Node x l r) -- match tree
(_:xs) -- match nonโempty list
-- wildcard
_ -- ignore value