Add map slides

This commit is contained in:
Julian Ospald 2015-04-19 17:56:12 +02:00
parent 2f6a14e943
commit 1864eb1ca5
No known key found for this signature in database
GPG Key ID: 220CD1C5BDEED020
1 changed files with 63 additions and 2 deletions

65
VL2.tex
View File

@ -389,7 +389,14 @@ Since we use lists a lot in haskell, we also want some more powerful functions t
\item ...
\end{itemize}
\pause
How do we do that? Let's say we have a list of \code{Int} and want to add \code{2} to every element of the list.
How do we do that?
\end{frame}
\subsection{6.1. map}
\begin{frame}[fragile]
\frametitle{6.1. map}
Let's say we have a list of \code{Int} and want to add \code{2} to every element of the list.
\begin{haskellcode}
addTwo :: [Int] -> [Int]
addTwo ... ?
@ -399,13 +406,67 @@ addTwo ... ?
\end{frame}
\begin{frame}[fragile]
\frametitle{5. Recursion patterns (ctn.)}
\frametitle{6.1. map (ctn.)}
Solution?
\begin{haskellcode}
addTwo :: [Int] -> [Int]
addTwo [] = []
addTwo (x:xs) = (x + 2) : addTwo xs
\end{haskellcode}
\pause
Now we want to square every element:
\pause
\begin{haskellcode}
square :: [Int] -> [Int]
square [] = []
square (x:xs) = (x * x) : square xs
\end{haskellcode}
\pause
Now we want the absolute of every element:
\begin{haskellcode}
absList :: [Int] -> [Int]
absList [] = []
absList (x:xs) = (abs x) : absList xs
\end{haskellcode}
\pause
Do you notice something?
\end{frame}
\begin{frame}[fragile]
\frametitle{6.1. map (ctn.)}
All those 3 functions look almost the same. Since haskell is about abstraction, we would never really write any of those like that. Instead, we will write a function that generalizes all 3.
\vspace{\baselineskip}
\\
\pause
I'll give you the type signature, can you guess how the implementation looks like?
\begin{haskellcode}
map :: (a -> b) -> [a] -> [b]
\end{haskellcode}
Solution?
\pause
\begin{haskellcode}
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs
\end{haskellcode}
So we don't really know what the function \code{f} does, but we know that it converts one element of the list to something else. We \emph{map} a function over a list! Hence the name.
\end{frame}
\begin{frame}[fragile]
\frametitle{6.1. map (ctn.)}
And now watch this:
\begin{haskellcode}
addTwo :: [Int] -> [Int]
addTwo xs = map (\x -> x + 2) xs
square :: [Int] -> [Int]
square xs = map (\x -> x * x) xs
absList :: [Int] -> [Int]
absList xs = map (\x -> abs x) xs
\end{haskellcode}
\pause
Cool, right? So now we have abstracted out the \textbf{recursion pattern} that is all the same for those 3 functions. \code{map} is actually part of the standard library (called \emph{Prelude}).
\end{frame}
\end{document}