Skip to content

Notes for Week 17 More Monads Part 1

mattcallanan edited this page Apr 10, 2012 · 21 revisions

Links:

Exercises:

Exercise 1

Write a simple program that iterates through a List and uses the WriterMonad to log the progress of each item within the list. Add the word: "Complete" to the end of your log once the List has been traversed.

Use the following function definition as a starting point if desired:

count :: (Show a) => [a] -> Writer [String] ()

An example run with: count [1..10] would look like:

runWriter $ count [1..10]
((),["value: 1","value: 2","value: 3","value: 4","value: 5","value: 6","value: 7","value: 8","value: 9","value: 10","Complete"])

Exercise 2

Using java.lang.StringBuilder as an example, create a "Buffer" instance of Monad. Create an append function such that:

testAppend1 = (return "abc" >>= append "123" >>= append "xyz") == (Buffer "abc123xyz")

testAppend2 = (return [1,1,1] >>= append [2,2,2] >>= append [3,3,3]) == (Buffer [1,1,1,2,2,2,3,3,3])

Make sure your Buffer instance adheres to the Monad laws.

What is the context maintained by this Monad?

Discuss whether this valid Monadic instance or just an instance of another well-known Monad.

hint you may have to make your structure polymorphic unlike StringBuilder.

Questions raised during the group:

Answers to Exercises:

1.

Steve's Solution

import Control.Monad.Writer
count :: (Show a) => [a] -> Writer [String] ()
count x =  mapM (\y -> writer ((), ["Got number: " ++ show y])) x >> tell ["Complete"]   
exercise1 = runWriter $ count [1..10]

Interesting Asides

Clone this wiki locally