public
Last active

Monad

  • Download Gist
gistfile1.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
type Choice a = [a]
 
choose :: [a] -> Choice a
choose xs = xs
 
-- Join
join :: Choice (Choice a) -> Choice a
join choices = concat choices
 
-- Bind
(>>=) :: Choice a -> (a -> Choice b) -> Choice b
choices >>= f = join (map f choices)
 
-- Bind (ignore original)
(>>) :: Choice a -> Choice b -> Choice b
choices >> f = choices >>= \_ -> f
 
-- Return
return :: a -> Choice a
return x = choose [x]
 
-- Guard
mzero :: Choice a
mzero = choose []
 
guard :: Bool -> Choice ()
guard True = return ()
guard False = mzero
 
test' :: Choice (Int, Int, Int)
test' = do
x <- choose [1,2,3]
y <- choose [4,5,6]
z <- choose [7,8,9]
guard ((x + y) * z == 45)
return (x, y, z)
 
main = do
print(take 1 test')

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.