haskell-lectures/VL2/content/VL2_fold2.tex

19 lines
748 B
TeX
Raw Normal View History

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)
\end{haskellcode}
Whoa! What's going on here?\\
Let's see...
\begin{itemizep}
\item \hinline{z} is what we return if the list is empty
\item \hinline{f} is our function (e.g. \hinline{(*)} or \hinline{(+)})
\item and the last remaining argument is the actual list we are working on
\end{itemizep}
\slidep
The function application has the following form:\\
\hinline{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}.