Created
November 25, 2016 03:17
-
-
Save friedbrice/a2912285559c5b296d782630ccd79a76 to your computer and use it in GitHub Desktop.
Haskell `List` standard instances implemented in terms of `foldr`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
foldr
is a catamorphism ofList
, which I'll explain in a blog post once I get around to learning what a "catamorphism" is.