Skip to content

Instantly share code, notes, and snippets.

@5outh
5outh / shortest.hs
Last active December 10, 2015 20:28
shortest :: (Num a, Ord a) => Tree a -> a
shortest (Leaf x) = x
shortest (Node x xs) = x + (minimum $ map shortest xs)
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
data Tree a = Node a [Tree a] | Leaf a deriving (Show, Eq)
instance Functor Tree where
fmap f (Leaf a) = Leaf $ f a
fmap f (Node a b) = Node (f a) (map (fmap f) b)
@5outh
5outh / Comonad.hs
Created January 7, 2013 21:34
Comonad
class (Functor w) => Comonad w where
coreturn :: w a -> a
cojoin :: w a -> w (w a)
(=>>) :: w a -> (w a -> b) -> w b
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
@5outh
5outh / List.hs
Last active December 10, 2015 06:08
instance Monad [] where
return x = [x]
xs >>= f = concatMap f xs
instance Monad Maybe where
return = Just
Nothing >>= f = Nothing
(Just a) >>= f = f a
@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
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
@5outh
5outh / sums.hs
Created December 27, 2012 21:03
sums = sample =>> addTree