Module 03: Polymorphism and Lists

In this module we will complete our initial exploration of the Haskell programming language. For today, choose whoever you wish to start as the driver.

Maybe

data Maybe a where
  Nothing :: Maybe a
  Just    :: a -> Maybe a

Note that the above definition of Maybe does not have bird tracks in front of it since it is already defined in the standard library; I just wanted to show you its definition.

> w :: Maybe Int
> w = Just 3
> 
> x :: Maybe String
> x = Just "hello"
> 
> y :: Maybe Char
> y = Nothing
> 
> z :: Maybe (Maybe Int)
> z = Just Nothing
> 
> safeDiv :: Integer -> Integer -> Maybe Integer
> safeDiv _ 0 = Nothing
> safeDiv x y = Just (x `div` y)
> 
> showDiv :: Integer -> Integer -> String
> showDiv x y = case safeDiv x y of
>   Nothing -> "Division by zero"
>   Just z  -> "Result is " ++ show z

When you reach this point, STOP and let Dr. Yorgey know.

Lists

ROTATE ROLES

> ints :: [Integer]
> ints = [3, 5, 92]
> 
> noInts :: [Integer]
> noInts = []
> 
> moreInts :: [Integer]
> moreInts = 7 : ints
> 
> yetMoreInts :: [Integer]
> yetMoreInts = 4 : 2 : ints
> 
> someInts :: [Integer]
> someInts = 8 : 42 : noInts
> 
> ints2 :: [Integer]
> ints2 = 3 : 5 : 92 : []

When you reach this point, STOP and let Dr. Yorgey know.

Strings

ROTATE ROLES

> greeting :: String
> greeting = "Hello"
> 
> greeting2 :: String
> greeting2 = ['H','e','l','l','o']
> 
> greeting3 :: [Char]
> greeting3 = ['H','e','l','l','o']
> 
> everyone :: String
> everyone = "world"

(You know the drill)

List pattern matching

ROTATE ROLES

> listLength []     = (0 :: Integer)
> listLength (_:xs) = 1 + listLength xs
> 
> startsWith :: String -> String -> Bool
> startsWith []     _      = undefined
> startsWith (_:_)  []     = undefined
> startsWith (x:xs) (y:ys) = undefined