Skip to content

Commit

Permalink
List Monad. MonadPlus. Guard for filter monadic operations.
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabi Volpe committed Aug 22, 2016
1 parent 01aec7b commit 11935ac
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions category-theory/monad.hs
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,60 @@ wopwop :: Maybe Char
wopwop = do
(x:xs) <- Just ""
return x

-- Monad instance for List
-- instance Monad [] where
-- return x = [x]
-- xs >>= f = concat (map f xs)
-- fail _ = []

-- examples on lists
g1 = [3,4,5] >>= \x -> [x,-x]

-- fail is defined as an empty list
g2 = [] >>= \x -> ["bad","mad","rad"]
g3 = [1,2,3] >>= \_ -> []

-- chaining monadic operations on list
g4 = [1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch)

-- same as g4 written using do notation
listOfTuples :: [(Int,Char)]
listOfTuples = do
n <- [1,2]
ch <- ['a','b']
return (n,ch)

-- same as g4 using List comprehension (syntax sugar for using lists as monads)
listOfTuplesC = [ (n,ch) | n <- [1,2], ch <- ['a','b'] ]

-- filtering a list
filteredList = [ x | x <- [1..50], '7' `elem` show x ]

-- MonadPlus definition
class Monad m => MonadPlus m where
mzero :: m a
mplus :: m a -> m a -> m a

-- MonadPlus instance of List
instance MonadPlus [] where
mzero = []
mplus = (++)

guard :: (MonadPlus m) => Bool -> m ()
guard True = return ()
guard False = mzero

-- filter example using guard
h1 = guard (5 > 2) :: [()]
h2 = guard (5 > 2) >> return "cool" :: [String]
h3 = guard (1 > 2) >> return "cool" :: [String]

-- filter list using Monad
filteredListMonadic = [1..50] >>= (\x -> guard ('7' `elem` show x) >> return x)

sevensOnly :: [Int]
sevensOnly = do
x <- [1..50]
guard ('7' `elem` show x) -- filter
return x

0 comments on commit 11935ac

Please sign in to comment.