Skip to content

Instantly share code, notes, and snippets.

@cheecheeo
Created December 6, 2012 22:53
Show Gist options
  • Save cheecheeo/4229221 to your computer and use it in GitHub Desktop.
Save cheecheeo/4229221 to your computer and use it in GitHub Desktop.
Applicative functors exercise
{-# LANGUAGE TypeOperators, ScopedTypeVariables #-}
-- http://stackoverflow.com/questions/10239630/where-to-find-programming-exercises-for-applicative-functors
-- http://stackoverflow.com/a/10242673/1019205
import Control.Applicative (Applicative, pure, (<$>), (<*>))
import Data.Foldable (Foldable, foldMap)
import Data.Traversable (Traversable, sequenceA)
import Data.Monoid ((<>))
data Triple a =
Tr a a a
deriving (Show)
newtype (:.) f g x =
Comp {comp :: f (g x)}
deriving (Show)
instance Functor Triple where
fmap f (Tr x y z) = Tr (f x) (f y) (f z)
instance Foldable Triple where
foldMap f (Tr x y z) = f x <> f y <> f z
instance Applicative Triple where
pure x = Tr x x x
(Tr f g h) <*> (Tr x y z) = Tr (f x) (g y) (h z)
instance Traversable Triple where
sequenceA (Tr f g h) = Tr <$> f <*> g <*> h
instance (Functor f, Functor g) => Functor (f :. g) where
fmap f (Comp x) = Comp $ fmap (fmap f) x
instance (Applicative f, Applicative g) => Applicative (f :. g) where
pure x = Comp (pure (pure x))
--(Comp f) <*> (Comp x) = Comp $ f x
{-
instance (Traversable f, Traversable g) => Traversable (f :. g) where
-}
main :: IO ()
main = do
x :: Triple String <- sequenceA $ pure getLine
print x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment