Skip to content

Instantly share code, notes, and snippets.

data Tree a = Node a [Tree a] | Leaf a deriving (Show, Eq)
sample = Node 1 [Node 2 [Leaf 5, Leaf 6], Node 3 [Leaf 7], Node 4 [Leaf 8]]
reduce f (Leaf x) = x
reduce f (Node x xs) = f x . foldr1 f $ map (reduce f) xs
addTree = reduce (+)
multTree = reduce (*)
class (Functor w) => Comonad w where
coreturn :: w a -> a
cojoin :: w a -> w (w a)
(=>>) :: w a -> (w a -> b) -> w b
instance Functor Tree where
fmap f (Leaf a) = Leaf $ f a
fmap f (Node a b) = Node (f a) (map (fmap f) b)
instance Comonad Tree where
coreturn (Leaf a) = a
coreturn (Node a _) = a
cojoin l@(Leaf a) = Leaf l
cojoin n@(Node a b) = Node n (map cojoin b)
x =>> f = fmap f $ cojoin x
@5outh
5outh / sums.hs
Created December 27, 2012 21:03
sums = sample =>> addTree
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
@5outh
5outh / Identity.hs
Last active December 10, 2015 06:08
data Identity a = Identity a deriving Show
instance Monad Identity where
return = Identity
(Identity a) >>= f = f a
m1 = Identity 3
addThree x = return $ x+3
bindExample1 = m1 >>= addThree
instance Monad Maybe where
return = Just
Nothing >>= f = Nothing
(Just a) >>= f = f a
@5outh
5outh / List.hs
Last active December 10, 2015 06:08
instance Monad [] where
return x = [x]
xs >>= f = concatMap f xs
instance Monad ((->) r) where
return = const
{-Note:
(>>=) :: (r -> a) -> (a -> (r -> b)) -> (r -> b)
f :: (r -> a)
g :: (a -> (r -> b))
-}
f >>= g = \r -> g (f r) r
-- using >>= and lambda functions