In the exercises and assignments, you may have made use of the >> operator. If not, here is its implementation:
(>>) :: (Monad m) => m t -> m u -> m u
a >> b = a >>= (\_ -> b)It behaves identically to >>=, except that it discards the result of the first monadic operation.
-
Prove by careful equational reasoning that
>>is associative, i.e.(a >> b) >> c == a >> (b >> c). -
Give an example to explain why
>>=must be left-associative.
-
The hard part is the monad law step:
(a >> b) >> c = (a >>= (\_ -> b)) >> c -- definition = (a >>= (\_ -> b)) >>= (\_ -> c) -- definition = a >>= (\x -> (\_ -> b) x >>= (\_ -> c)) -- monad law: associativity = a >>= (\_ -> b >>= (\_ -> c)) -- simplification: \x -> (\_ -> b) x == \_ -> b = a >>= (\_ -> b >> c) -- definition = a >> (b >> c) -- definition
-
Because right-associativity would potentially cause type errors in seemingly valid use cases:
(["hi", "cs3141"] >>= words) >>= reverse == "ih1413sc" ["hi", "cs3141"] >>= (words >>= reverse) == ???
A function
g :: [a] -> bis said to be a fold if there exists a functionf :: a -> b -> band valuex :: bsuch thatfsatisfiesUse structural induction to prove the following universality theorem: if
gsatisfies the fold equations for somefandx, theng = foldr f x.We use structural induction on
ys :: [a]to show thatg ys = foldr f x ys.In the base case
ys = [], by the first fold property and the definition offoldr, we haveg [] = foldr f x [].In the inductive case, write
ys = y:ys'and assume as an inductive hypothesis thatg ys' = foldr f x ys'. ThenThus,
g = foldr f xfor all input listsys :: [a].It is trivial to see that
foldr f xis a fold, so we have proved the universal property of fold: this is the unique fold.