Created
June 26, 2018 05:31
-
-
Save scalolli/6fd86f72566fadcc7173048e2cb68fdf to your computer and use it in GitHub Desktop.
List Traversable and Const Applicative
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
import Data.Monoid | |
data List' a = Nil' | Cons' a (List' a) deriving (Eq, Show) | |
instance Monoid (List' a) where | |
mempty = Nil' | |
mappend x Nil' = x | |
mappend Nil' x = x | |
mappend (Cons' a xs) ys = Cons' a $ xs <> ys | |
instance Functor List' where | |
fmap _ Nil' = Nil' | |
fmap f (Cons' x y) = Cons' (f x) $ fmap f y | |
instance Applicative List' where | |
pure f = Cons' f Nil' | |
Nil' <*> x = Nil' | |
y <*> Nil' = Nil' | |
(Cons' f xs) <*> ys = (f <$> ys) <> (xs <*> ys) | |
instance Foldable List' where | |
foldMap f (Cons' x xs) = (f x) <> (foldMap f xs) | |
instance Traversable List' where | |
traverse f Nil' = pure mempty | |
traverse f (Cons' x xs) = ((\x y -> Cons' x y) <$> f x <*> traverse f xs) | |
-- So the first part from the List traversable | |
(\x -> Cons' x Nil') <$> (Const $ Sum 1) | |
-- will give us Const (Sum {getSum = 1}) since Const drops the second value | |
-- So the expression becomes | |
(Const $ Sum 1) <*> (Const $ Sum 2) <*> (Const $ Sum 3) | |
-- It ends up using the monoid instance of Sum to combine so Const $ Sum 6 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment