Reading — step 1 of 5
Learn
~1 min readControl Flow
Haskell has no for or while — there's no mutable state to advance. Iteration is recursion.
sumTo :: Int -> Int
sumTo 0 = 0
sumTo n = n + sumTo (n - 1)
This is two equations of sumTo — the compiler tries patterns top-to-bottom. The base case (sumTo 0 = 0) terminates the recursion.
List recursion uses the (x:xs) pattern (x is the head, xs is the rest):
length' :: [a] -> Int
length' [] = 0
length' (_:xs) = 1 + length' xs
In practice, you rarely write recursion by hand — the standard library has higher-order functions (map, filter, foldr, foldl) that abstract the common patterns:
sumTo n = sum [1..n]
sumTo n = foldr (+) 0 [1..n]
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…