haskell-lectures/VL2/content/VL2_fold4.tex

18 lines
854 B
TeX
Raw Normal View History

There is also a function that folds from the \emph{left} which is also in the \emph{Prelude} and called \textbf{foldl}.\\
To summarize:
\begin{haskellcode}
foldr f z [a,b,c] == a `f` (b `f` (c `f` z))
foldl f z [a,b,c] == ((z `f` a) `f` b) `f` c
\end{haskellcode}
For \hinline{foldl} the \hinline{z} is sort of the starting value.
\vspace{\baselineskip}
\\
\pause
We can even express foldl in terms of foldr and vice versa. If you are interested, have a look here:\\ \url{http://lambda.jstolarek.com/2012/07/expressing-foldl-in-terms-of-foldr/}
\vspace{\baselineskip}
\\
You should definitely look them up in the Prelude and play with them: \url{https://hackage.haskell.org/package/base-4.8.0.0/docs/Prelude.html}
\begin{haskellcode*}{bgcolor=mygrey,frame=single,numbers=none,label=GHCi}
> foldr (-) 0 [1, 2, 3]
> foldl (-) 0 [1, 2, 3]
\end{haskellcode*}