Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Last active April 16, 2021 00:54
Show Gist options
  • Save pedrominicz/a571d8f03726ed06022ecd745936155a to your computer and use it in GitHub Desktop.
Save pedrominicz/a571d8f03726ed06022ecd745936155a to your computer and use it in GitHub Desktop.
Another list monad
module List where
data List a = Nil | Cons a (List a) deriving (Eq, Show)
instance Functor List where
fmap f Nil = Nil
fmap f (Cons a as) = Cons (f a) (fmap f as)
instance Applicative List where
pure a = Cons a Nil
(<*>) = undefined
append :: List a -> List a -> List a
append (Cons a as) bs = Cons a (append as bs)
append Nil bs = bs
join :: List (List a) -> List a
join Nil = Nil
join (Cons l ls) = append (join ls) l
instance Monad List where
a >>= f = join $ fmap f a
toList :: [a] -> List a
toList [] = Nil
toList (a:as) = Cons a (toList as)
fromList :: List a -> [a]
fromList Nil = []
fromList (Cons a as) = a : fromList as
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment