# Week 9

### Lecture slides

- Monads, continued from Week 8. The videos go into the desugarion
of IO action into Worlds -- watch them!
- Intro to constant-time: pdf, key,

### Recommended reading

### Code snippets

#### Implementing wc in Haskell

module Main (main) where
import System.Environment
getFilename :: IO String
getFilename = do
args <- getArgs
case args of
(arg:_) -> return arg
_ -> fail "missing arg"
main :: IO ()
main = do
fname <- getFilename
putStrLn $ "processing " ++ fname
contents <- readFile fname
putStrLn $ "lines: " ++ show (length $ lines contents)
putStrLn $ "words: " ++ show (length $ words contents)

#### Functor-like type class

{-# LANGUAGE InstanceSigs #-}
module HasMap where
import Prelude hiding (map)
mapList :: (a -> b) -> [a] -> [b]
mapList f [] = []
mapList f (x:xs) = f x : mapList f xs
mapMaybe :: (a -> b) -> Maybe a -> Maybe b
mapMaybe f Nothing = Nothing
mapMaybe f (Just x) = Just (f x)
data Tree a = Leaf a
| Node (Tree a) (Tree a)
mapTree :: (a -> b) -> Tree a -> Tree b
mapTree f (Leaf x) = Leaf (f x)
mapTree f (Node t1 t2) = Node (mapTree f t1) (mapTree f t2)
class HasMap g where
map :: (a -> b) -> g a -> g b
instance HasMap [] where
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs
instance HasMap Maybe where
map = mapMaybe
instance HasMap Tree where
map = mapTree