From 11935ac2910c04e2775bfde896ccf84f0fb78d25 Mon Sep 17 00:00:00 2001 From: Gabi Volpe Date: Mon, 22 Aug 2016 17:02:20 +0100 Subject: [PATCH] List Monad. MonadPlus. Guard for filter monadic operations. --- category-theory/monad.hs | 57 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/category-theory/monad.hs b/category-theory/monad.hs index 9b50527..9baf1f0 100644 --- a/category-theory/monad.hs +++ b/category-theory/monad.hs @@ -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