From 6588473adf96a3eb7cfac55820ec022d4533fcbf Mon Sep 17 00:00:00 2001 From: Joe Zhao Date: Mon, 24 Aug 2015 15:45:45 -0600 Subject: Foldables --- foldables/h1.hs | 6 ++++++ monad/h1.hs | 3 +++ monad/h2.hs | 5 +++++ monad/h21.hs | 3 +++ monad/h3.hs | 11 +++++++++++ monadTrans/h1.hs | 2 ++ monadTrans/h2.hs | 4 ++++ 7 files changed, 34 insertions(+) create mode 100644 foldables/h1.hs create mode 100644 monad/h1.hs create mode 100644 monad/h2.hs create mode 100644 monad/h21.hs create mode 100644 monad/h3.hs create mode 100644 monadTrans/h1.hs create mode 100644 monadTrans/h2.hs diff --git a/foldables/h1.hs b/foldables/h1.hs new file mode 100644 index 0000000..16b22ac --- /dev/null +++ b/foldables/h1.hs @@ -0,0 +1,6 @@ +-- What is the type of foldMap . foldMap? Or foldMap . foldMap . foldMap, etc.? What do they do? + +foldMap :: Monoid m => (a -> m) -> t a -> m + +foldMap . foldMap :: (Foldable t, Foldable t1, Monoid m) => (a -> m) -> t (t1 a) -> m +-- They fold for multi-level of foldables diff --git a/monad/h1.hs b/monad/h1.hs new file mode 100644 index 0000000..a6cc093 --- /dev/null +++ b/monad/h1.hs @@ -0,0 +1,3 @@ +instance Monad [] where + return a = [a] + (>>=) as f = concatMap f as diff --git a/monad/h2.hs b/monad/h2.hs new file mode 100644 index 0000000..fce9d81 --- /dev/null +++ b/monad/h2.hs @@ -0,0 +1,5 @@ +instance Monad ((->) e) where + return f = \_ -> f + (>>=) f1 f2 = \r -> f2 (f1 r) r + -- f1 :: m a + -- f2 :: a -> m b diff --git a/monad/h21.hs b/monad/h21.hs new file mode 100644 index 0000000..c843dcb --- /dev/null +++ b/monad/h21.hs @@ -0,0 +1,3 @@ +(>>=) m f = join $ fmap f m +join x = x >>= id +fmap f x = x >>= (return . f) diff --git a/monad/h3.hs b/monad/h3.hs new file mode 100644 index 0000000..9439331 --- /dev/null +++ b/monad/h3.hs @@ -0,0 +1,11 @@ +data Free f a = Var a + | Node (f (Free f a)) + +instance Functor f => Functor (Free f) where + fmap g (Var a) = g a + fmap g (Node a) = fmap g a + +instance Functor f => Monad (Free f) where + return a = Var a + (Var a) >>= g = g a + (Node a) >>= g = fmap g a diff --git a/monadTrans/h1.hs b/monadTrans/h1.hs new file mode 100644 index 0000000..0127e8c --- /dev/null +++ b/monadTrans/h1.hs @@ -0,0 +1,2 @@ +-- Kind of t in MonadTrans t +(* -> *) -> * -> * diff --git a/monadTrans/h2.hs b/monadTrans/h2.hs new file mode 100644 index 0000000..b74c1e1 --- /dev/null +++ b/monadTrans/h2.hs @@ -0,0 +1,4 @@ +-- Implement join :: M (N (M (N a))) -> M (N a), given distrib :: N (M a) -> M (N a) and assuming M and N are instances +-- of Monad. + +join a = fmap join (join $ fmap distrib a) -- cgit v1.2.3-70-g09d2