Skip to content

Instantly share code, notes, and snippets.

@nodew
Last active June 2, 2018 02:18
Show Gist options
  • Save nodew/362792f3497aa0b6165d14826b9e1b01 to your computer and use it in GitHub Desktop.
Save nodew/362792f3497aa0b6165d14826b9e1b01 to your computer and use it in GitHub Desktop.
a monad is just a monoid in the category of endofunctors
{-# LANGUAGE RankNTypes #-}
module Main where
import Prelude hiding (Monad(..), Monoid(..))
-- class Monoid m where
-- mempty :: m
-- mappend :: m -> m -> m
-- mconcat :: [m] -> m
-- mconcat = foldr mappend mempty
-- class Foldable t where
-- foldr :: (a -> b -> b) -> b -> t a -> b
class (Functor w, Foldable w) => MyMonoid w where
mempty :: w a
mappend :: w a -> w a -> w a
mconcat :: w (w a) -> w a
mconcat = foldr mappend mempty
class MyMonoid m => Monad m where
return :: a -> m a
infixl 1 >>=
(>>=) :: forall a b. m a -> (a -> m b) -> m b
infixl 1 >>
(>>) :: forall a b. m a -> m b -> m b
ma >> mb = ma >>= \_ -> mb
ma >>= f = mconcat $ fmap f ma
-------------------------------------------------------
data List a = Null | Cons a (List a) deriving (Show)
instance Functor List where
fmap _ Null = Null
fmap f (Cons x rest) = Cons (f x) (fmap f rest)
instance Foldable List where
foldr _ x Null = x
foldr f x (Cons b Null) = f b x
foldr f x (Cons b rest) = f b (foldr f x rest)
instance MyMonoid List where
mempty = Null
mappend Null b = b
mappend (Cons a rest) b = Cons a (mappend rest b)
instance Monad List where
return x = Cons x Null
main:: IO ()
main = putStrLn $ show $ ((Cons 1 (Cons 2 (Cons 3 Null))):: List Int)
>>= \x -> (return $ x * 2)
>>= \y -> return $ show y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment