Exercise set 4 - from PIH
Exercise 1
Define an action adder :: IO () that reads a given number of integers from the keyboard, one per line, and displays their sum. For example:
> adder
How many numbers? 5 1
3
5
7
9
The total is 25
Exercise 2
Redefine adder using the function sequence :: [IO a] -> IO [a] that performs a list of actions and returns a list of the resulting values.
Exercuse 3
Define an instance of the Functor class for the following type of binary trees that have data in their nodes:
data Tree a = Leaf | Node (Tree a) a (Tree a) deriving Show
Exercise 4
There may be more than one way to make a parameterised type into an applicative functor. For example, the library Control.Applicative provides an alternative ‘zippy’ instance for lists, in which the function pure makes an infinite list of copies of its argument, and the operator <*> applies each argument function to the corresponding argument value at the same position. Complete the following declarations that implement this idea:
newtype ZipList a = Z [a]
deriving Show
instance Functor ZipList where
-- fmap :: (a -> b) -> ZipList a -> ZipList b
fmap g (Z xs) = ...
instance Applicative ZipList where
-- pure :: a -> ZipList a
pure x = ...
-- <*> :: ZipList (a -> b) -> ZipList a -> ZipList b
(Z gs) <$> (Z xs) = ...
The ZipList wrapper around the list type is required because each type can only have at most one instance declaration for a given class.
Exercise 4
Define an instance of the Functor class for the following type of binary trees that have data in their nodes:
data Tree a = Leaf| Node (Tree a) a (Tree a) deriving Show
Exercise 5
Given the following type of expressions
data Expr a = Var a | Val Int | Add (Expr a) (Expr a)
deriving Show
that contain variables of some type a, show how to make this type into in- stances of the Functor, Applicative and Monad classes. With the aid of an example, explain what the >>= operator for this type does.