Skip to content

Notes from Week 18 More Monads Part 2

ssanj edited this page Apr 10, 2012 · 15 revisions

Links:

Exercises:

Exercise 1

Given the WriterMonad and the StateMonad can both store some kind of state, compare and contrast the two monads and explain where you would use one over the other.

Exercise 2

Given the following:

import Control.Monad.State

data Queue a = EmptyQ | Q[a] deriving (Show, Eq)

colours = ["red", "green", "blue", "yellow", "magenta", "teal", "burgundy", "gray"]
numbers = [1..100]

testColours = (((runState stateColours) $ Q(colours)) == ((), Q["red", "green", "magenta"]))    
testNumbers = (((runState stateNumbers) $ Q(numbers)) == ((), Q[404]))

stateColours :: State (Queue String) ()
stateColours = do
  enqueue "maroon"
  enqueue "scarlet"
  filQ ('l' `notElem`)
  dequeue
  filQ('e' `elem`)

stateNumbers :: State (Queue Int) ()
stateNumbers  = do
  dequeue
  dequeue
  filQ (\x -> x >= 40 && x <= 50)
  enqueue 101
  filQ (\x -> x `mod` 2 == 0)
  dequeue
  dequeue
  filQ (\x -> x `mod` 2 /= 0)
  enqueue 404

write implementations for the following:

enqueue :: a -> State (Queue a) ()  --adds an element to the end of the Queue
dequeue :: State (Queue a) ()  --removes the last element
filQ ::(Eq a) => (a -> Bool) -> State (Queue a) () --returns elements of the Queue that satisfy the predicate

such that testNumbers and testColours return True.

Exercise 3

What would we gain/lose if we implemented the above exercise without the State Monad?

Questions raised during the group:

Code becomes:

pop :: State Stack Int
pop = state $ \(x:xs) -> (x,xs) 

push :: Int -> State Stack ()  
push a = state $ \xs -> ((), a:xs) 

Answers to Exercises:

//TODO

Interesting Asides

Clone this wiki locally