3 ms·
I've never really done anything seriously in Haskell, but this is how I feel monads could be explained through example. Let me know what you guys think. If it's
by hmexx 12y ago
I've never really done anything seriously in Haskell, but this is how I feel monads could be explained through example. Let me know what you guys think. If it's good I'll add it to the stackoverflow question on Monads.
---
We know how operators (add, substract, multiply,...) work on integers. example: 5 + 6 = 11.
Now let's add some extra state/dimension to integers. Let's assume this extra state is ROCK, PAPER or SCISSORS.
Here are possible values:
5_ROCK
6_PAPER
999_SCISSOR
...etc...
---
What is the result of 5_ROCK + 6_PAPER ?
There is no answer unless someone defines it. That's what a monad does. In this case I am deciding that 5_ROCK + 6_PAPER = 11_PAPER
The way MY monad works is to use the operator on the integer portion ( 5 + 6) and then use the winner of ROCK, PAPER, SCISSORS game as the non-integer portion.
3_ROCK * 4_SCISSOR = 12_ROCK
8_SCISSOR / 2_PAPER = 4_SCISSOR
...etc...
- tome 12y agoSo what is `return` (also known as `pure` or `unit`) and does it satisfy the monad laws?
- dllthomas 12y agoI think you might be confused, because this really doesn't touch on monads at all. You can implement it by just defining an instance of the Num typeclass for your new data type: data RPS = Rock | Paper | Scissors data IRps = IRps Integer RPS fight Rock Paper = Paper fight Rock Scissors = Rock fight Paper Scissors = Scissors fight Rock Rock = Rock fight Paper Paper = Paper fight Scissors Scissors = Scissors fight x y = fight y x instance Num IRps where IRps x x' + IRps y y' = IRps (x + y) (fight x' y') Of course, with the lack of associativity, I'd weakly discourage a Num instance too, but that's not adhered to perfectly already.