-
Notifications
You must be signed in to change notification settings - Fork 5
Notes for Week 17 More Monads Part 1
- Online chapter
- All about Monads
- Monad tutorials timeline
- Functional Dependencies SO
- Functional Dependencies Haskell Docs
- Type Families Haskell Docs
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"])
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.
- Difference between Writer and WriterT: http://stackoverflow.com/questions/7630350/writer-vs-writert-in-haskell
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]
- Why Cowboys
- [Learning Haskell and Python makes you a worse programmer] (http://lukeplant.me.uk/blog/posts/why-learning-haskell-python-makes-you-a-worse-programmer/)
- [Groovy monads] (https://github.com/dsrkoc/monadologie)
- [Tony's blog about Writer monad in Scala] (http://blog.tmorris.net/the-writer-monad-using-scala-example/)
- [Tony's Writer Monad] (https://github.com/tonymorris/writer-monad)
- "The concept might be a little tricky to grasp: monads are like ordinary monoids, but with outer and inner replacing left and right. But the payoff from this is that intuitions about monoids carry over to monads."