Skip to content

Instantly share code, notes, and snippets.

@friedbrice
Created November 25, 2016 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save friedbrice/a2912285559c5b296d782630ccd79a76 to your computer and use it in GitHub Desktop.
Save friedbrice/a2912285559c5b296d782630ccd79a76 to your computer and use it in GitHub Desktop.
Haskell `List` standard instances implemented in terms of `foldr`
data List a = Empty | Cons a (List a) deriving (Eq, Read, Ord, Show)
instance Foldable List where
foldr _ acc Empty = acc
foldr f acc (Cons x xs) = f x (foldr f acc xs)
instance Functor List where
fmap f xs = foldr (\x acc -> Cons (f x) acc) Empty xs
instance Traversable List where
traverse f xs = foldr (\x acc -> (fmap Cons $ f x) <*> acc) (pure Empty) xs
instance Monoid (List a) where
mempty = Empty
xs `mappend` ys = foldr Cons ys xs
instance Applicative List where
pure x = Cons x Empty
fs <*> xs = foldr (\f acc -> (fmap f xs) `mappend` acc) Empty fs
instance Monad List where
xs >>= f = foldr (\x acc -> (f x) `mappend` acc) Empty xs
@friedbrice
Copy link
Author

foldr is a catamorphism of List, which I'll explain in a blog post once I get around to learning what a "catamorphism" is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment