haskell-lectures/VL2/content/VL2_rec_patterns9.tex
2015-04-20 15:06:54 +02:00

19 lines
733 B
TeX

To cut the story short, the abstract solution looks like this:
\begin{haskellcode}
fold :: b -> (a -> b -> b) -> [a] -> b
fold z f [] = z
fold z f (x:xs) = x `f` (fold z f xs)
\end{haskellcode}
Whoa! What's going on here?\\
Let's see...
\begin{itemizep}
\item \code{z} is what we return if the list is empty
\item \code{f} is our function (e.g. \code{(*)} or \code{(+)})
\item and the last remaining argument is the actual list we are working on
\end{itemizep}
\slidep
The function application has the following form:\\
\code{fold f z [a,b,c] == a `f` (b `f` (c `f` z))}
\vspace{\baselineskip}
\\
This folds from the right, so the \emph{Prelude} already defines a function which is very similar to ours and called \textbf{foldr}.