2015-04-19 22:32:50 +00:00
|
|
|
To cut the story short, the abstract solution looks like this:
|
|
|
|
\begin{haskellcode}
|
|
|
|
fold :: b -> (a -> b -> b) -> [a] -> b
|
|
|
|
fold z f [] = z
|
2015-04-20 13:06:54 +00:00
|
|
|
fold z f (x:xs) = x `f` (fold z f xs)
|
2015-04-19 22:32:50 +00:00
|
|
|
\end{haskellcode}
|
|
|
|
Whoa! What's going on here?\\
|
|
|
|
Let's see...
|
|
|
|
\begin{itemizep}
|
2015-04-20 18:55:41 +00:00
|
|
|
\item \hinline{z} is what we return if the list is empty
|
|
|
|
\item \hinline{f} is our function (e.g. \hinline{(*)} or \hinline{(+)})
|
2015-04-19 22:32:50 +00:00
|
|
|
\item and the last remaining argument is the actual list we are working on
|
|
|
|
\end{itemizep}
|
|
|
|
\slidep
|
|
|
|
The function application has the following form:\\
|
2015-04-20 18:55:41 +00:00
|
|
|
\hinline{fold f z [a,b,c] == a `f` (b `f` (c `f` z))}
|
2015-04-19 22:32:50 +00:00
|
|
|
\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}.
|