haskell-lectures/VL1/content/VL1_guards_and_recursion.tex
2015-04-21 18:47:51 +02:00

10 lines
669 B
TeX

How about \emph{recursion}? Let's define the modulo of any \emph{Int} to \emph{2}.
\pause
\begin{haskellcode}
mod2 :: Int -> Int
mod2 x
| x - 2 == 0 = 0
| x - 2 < 0 = x
| otherwise = mod2 (x - 2)
\end{haskellcode}
These \verb#|# things above are called \textbf{guards} and are similar to \emph{pattern matching}. They are processed in order. If the condition on the left side of the equation is true, then it returns what stands on the right side of the equation. If it's false, then it processes the next line.\\ \hinline{otherwise} on the last line is just defined as \hinline{True}, to make these constructs easier to read and catch all other cases of input.