Created
February 2, 2022 12:02
-
-
Save nobishino/b04cd36588f4ffaaa0755a1603774c32 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Monad laws and examples | |
-- Thanks to http://learnyouahaskell.com/a-fistful-of-monads#monad-laws | |
-- Left identity | |
-- return x >>= f equals to f x | |
l1 = return 3 >>= (\x -> Just (x + 100000)) | |
l2 = (\x -> Just (x + 100000)) 3 | |
l3 = return "WoM" >>= (\x -> [x,x,x]) | |
l4 = (\x -> [x,x,x]) "WoM" | |
-- Right identity | |
-- m >>= return equals to m | |
r1 = Just "Move on up" >>= return | |
r2 = Just "Move on up" | |
r3 = [1,2,3,4] >>= return | |
r4 = [1,2,3,4] | |
-- Left/Right identityはreturnのあるべきふるまいをきめる | |
-- Associativityは>>=の連鎖のあるべき振る舞い | |
-- Associativity | |
-- (m >>= f) >>= g equals to m >>= (\x -> f x >>= g) | |
type Birds = Int | |
type Pole = (Birds, Birds) | |
landLeft :: Birds -> Pole -> Maybe Pole | |
landLeft n (left, right) | |
| abs ((left + n) - right) < 4 = Just (left + n, right) | |
| otherwise = Nothing | |
landRight :: Birds -> Pole -> Maybe Pole | |
landRight n (left, right) | |
| abs ((left + n) - right) < 4 = Just (left, right + n) | |
| otherwise = Nothing | |
a0 = return (0,0) >>= landRight 2 >>= landLeft 2 >>= landRight 2 | |
a1 = ((return (0,0) >>= landRight 2) >>= landLeft 2) >>= landRight 2 | |
a11 = ((return (0,0) >>= landRight 2) >>= (landLeft 2) >>= landRight 2) | |
a2 = return (0,0) >>= (\x -> | |
landRight 2 x >>= (\y -> | |
landLeft 2 y >>= (\z -> | |
landRight 2 z))) | |
a3 = return (0,0) >>= landRight 2 >>= landLeft 2 | |
a4 = return (0,0) >>= (\x -> | |
landRight 2 x >>= (\y -> | |
landLeft 2 y)) | |
(.) :: (b -> c) -> (a -> b) -> (a -> c) | |
f . g = (\x -> f (g x)) | |
(<=<) :: (Monad m) => (b -> m c) -> (a -> m b) -> (a -> m c) | |
f <=< g = (\x -> g x >>= f) | |
f x = [x, -x] | |
g x = [x*3, x*2] | |
h = f <=< g | |
a5 = h 3 | |
-- f <=< (g <=< h) equals to (f <=< g) <=< h | |
-- monad laws with <=< | |
-- Left identity: f <=< return === f | |
-- Right identity: return <=< f === return | |
-- associative law: f <=< (g <=< h) === (f <=< g) <=< h |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
モナド則→その言い換えの証明