CS 330 Lecture 24 – Pattern Matching and List Comprehensions
Agenda
- what ?s
- functions
- capitalize (with guards, case, and pattern matching)
- tail’
- nbelows
- contains
- indexOf
- list comprehensions
- how to translate
TODO
- Bleakr’s due before April 6.
Note
Last time we mentioned that a primary theme of a functional language is that functions are a big deal. They can be stored in variables, they are a type, they can be sent as parameters and return values, they have their own literals (lambdas), and so on. We also saw that functional languages tend not to have imperative elements like loops. Instead, recursion is our mode of iteration.
Today we continue gaining experience writing Haskell functions. We’ll write a handful little utility functions and start to see some patterns emerge. Eventually, we will factor these patterns out to just a few higher-order functions that take in very small helper functions that do the custom work. One of the functions will be left as a program this:
Write a function
contains
that reports whether or not a list contains a certain element. Recall the type signature we wrote last time:contains :: (Eq a) => a -> [a] -> Bool
.
As we have time, we will also write a list comprehensions together.
Code
functions.hs
import Data.Char
capitalize2 :: String -> String
capitalize2 s
| s == "" = ""
| otherwise = toUpper (head s) : capitalize2 (tail s)
capitalize3 :: String -> String
capitalize3 s =
case s of
"" -> ""
(first:rest) -> toUpper first : capitalize3 rest
capitalize4 :: String -> String
capitalize4 "" = ""
capitalize4 (first:rest) = toUpper first : capitalize4 rest
tail' :: [a] -> [a]
tail' [] = error "Don't do that, please."
-- tail' (first:[]) = []
tail' (_:rest) = rest
nbelows :: (Ord a) => a -> [a] -> Integer
nbelows _ [] = 0
nbelows threshold (first:rest)
| first < threshold = 1 + nbelows threshold rest
| otherwise = nbelows threshold rest
contains :: (Eq a) => a -> [a] -> Bool
contains _ [] = False
contains needle haystack@(first:rest) = needle == first || contains needle rest