-
Notifications
You must be signed in to change notification settings - Fork 5
Notes from Week 18 More Monads Part 2
ssanj edited this page Apr 10, 2012
·
15 revisions
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.
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.
What would we gain/lose if we implemented the above exercise without the State Monad?
- Differences between MTL1 and MTL2:
- http://groups.google.com/group/comp.lang.haskell/browse_thread/thread/54df44267ec6a098?pli=1
- http://www.haskell.org/haskellwiki/Upgrading_from_MTL_1_to_MTL_2
Code becomes:
pop :: State Stack Int
pop = state $ \(x:xs) -> (x,xs)
push :: Int -> State Stack ()
push a = state $ \xs -> ((), a:xs)
//TODO
- Tony Morris: Patterns: Reduction to the Inconsequential
- IntelliJ Haskell Plugin
- [Clojure protocols compared to Haskell types] (http://debasishg.blogspot.com.au/2010/08/random-thoughts-on-clojure-protocols.html?m=1)
- Monad Transformers