| Safe Haskell | Safe-Inferred |
|---|
Lessons.Lesson07
Description
Notes taken by Emilija Rimšelytė
Synopsis
- lc :: [(Integer, Char)]
- lc' :: [Integer]
- lc'' :: [Integer]
- lc''' :: [Integer]
- lc'''' :: [Integer]
- lm :: [(Integer, Char)]
- lm' :: [(Integer, Char)]
- mm :: Maybe Integer
- mm' :: Maybe Integer
- mm'' :: Maybe Integer
- em :: Either String Char
- em' :: Either String Char
- em'' :: Either String (Integer, Char)
- em''' :: Either Integer Integer
- lmb :: [(Integer, Char)]
- mmb :: Maybe Integer
- emb :: Either String Char
Documentation
lc :: [(Integer, Char)] Source #
List comprehension: pairing numbers with letters.
For each a and b, we build a tuple.
A cartesian product, clean and subtle.
>>>lc[(1,'a'),(1,'b'),(2,'a'),(2,'b'),(3,'a'),(3,'b'),(4,'a'),(4,'b')]
Squares of a, repeated for each b.
b isn’t used, but it multiplies the count.
More combinations — that’s the amount.
>>>lc'[1,1,4,4,9,9]
b repeats for each c, though c is unused.
a is fixed, but nesting boosts the size.
>>>lc''[1,1,2,2,3,3,4,4]
Empty list in b means no results.
Comprehension short-circuits — nothing to compute.
>>>lc'''[]
Same idea, but now a is empty.
No values to pair, so the list stays bare.
>>>lc''''[]
lm :: [(Integer, Char)] Source #
Do-notation version of lc.
Same result, just written differently.
Shows how monads can express list logic.
>>>lm[(1,'a'),(1,'b'),(2,'a'),(2,'b'),(3,'a'),(3,'b'),(4,'a'),(4,'b')]
lm' :: [(Integer, Char)] Source #
Swapping the order changes the output.
First b, then a — so the nesting flips.
>>>lm'[(1,'a'),(2,'a'),(3,'a'),(4,'a'),(1,'b'),(2,'b'),(3,'b'),(4,'b')]
Maybe monad: chaining computations.
All values must be Just, or the chain breaks.
One Nothing, and the whole thing shakes.
>>>mmJust 84
One Nothing in the chain — result is Nothing.
That’s how Maybe guards against failure.
>>>mm'Nothing
mm'' :: Maybe Integer Source #
Looks like it should work, but it doesn’t. You need to bind the final value too. Just expression alone won’t pull it through.
>>>mm''Nothing
em :: Either String Char Source #
Either monad: Right flows like Maybe’s Just.
Left short-circuits — it’s an error path.
>>>emRight 'a'
em' :: Either String Char Source #
Left stops the computation early.
Doesn’t matter what comes after — it’s done.
>>>em'Left "oh"
em'' :: Either String (Integer, Char) Source #
You can return tuples too — Either handles it.
As long as all are Right, it’s alright.
>>>em''Right (43,'a')
em''' :: Either Integer Integer Source #
Mixing Left and Right — Left wins.
Error takes over, no multiplication begins.
>>>em'''Left 42
lmb :: [(Integer, Char)] Source #
Same as lm, but using >>= explicitly.
Do-notation is just syntactic sugar.
Shows the plumbing under the rug.
Same as mm, but written with >>=.
Shows how monads chain computations.
>>>mmbJust 84