Skip to content

Instantly share code, notes, and snippets.

@scalolli
Created June 26, 2018 05:31
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 scalolli/6fd86f72566fadcc7173048e2cb68fdf to your computer and use it in GitHub Desktop.
Save scalolli/6fd86f72566fadcc7173048e2cb68fdf to your computer and use it in GitHub Desktop.
List Traversable and Const Applicative
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