haskell-lectures/VL2/content/VL2_rec_patterns8.tex

25 lines
551 B
TeX

There's one more important recursion pattern. Imagine you want the sum of all numbers of a list, so the function type signature would be:
\begin{haskellcode}
sum :: [Int] -> Int
\end{haskellcode}
Solution?
\pause
\begin{haskellcode}
sum :: [Int] -> Int
sum [] = 0
sum (x:xs) = x + sum xs
\end{haskellcode}
\pause
Or the product:
\begin{haskellcode}
prod :: [Int] -> Int
prod [] = 1
prod (x:xs) = x * prod xs
\end{haskellcode}
\pause
Or the length:
\begin{haskellcode}
length :: [a] -> Int
length [] = 0
length (x:xs) = 1 + length xs
\end{haskellcode}