Last active
February 10, 2017 01:25
-
-
Save derekmorr/e82484f0ac159cd4bf61ec2851dcce66 to your computer and use it in GitHub Desktop.
ch17.hs
This file contains hidden or 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
module Ch17 where | |
import Control.Applicative | |
import Data.List (elemIndex) | |
import Data.Monoid | |
-- 1 | |
added :: Maybe Integer | |
added = (+3) <$> (lookup 3 $ zip [1, 2, 3] [4, 5, 6]) | |
-- 2 | |
y :: Maybe Integer | |
y = lookup 3 $ zip [1, 2, 3] [4, 5, 6] | |
z :: Maybe Integer | |
z = lookup 2 $ zip [1, 2, 3] [4, 5, 6] | |
tupled :: Maybe (Integer, Integer) | |
tupled = (,) <$> y <*> z | |
-- 3 | |
x' :: Maybe Int | |
x' = elemIndex 3 [1, 2, 3, 4, 5] | |
y' :: Maybe Int | |
y' = elemIndex 4 [1, 2, 3, 4, 5] | |
max' :: Int -> Int -> Int | |
max' = max | |
maxed :: Maybe Int | |
maxed = max' <$> x' <*> y' | |
maxed' :: Maybe Int | |
maxed' = liftA2 max' x' y' | |
-- 4 | |
xs = [1, 2, 3] | |
ys = [4, 5, 6] | |
x'' :: Maybe Integer | |
x'' = lookup 3 $ zip xs ys | |
y'' :: Maybe Integer | |
y'' = lookup 2 $ zip xs ys | |
summed :: Maybe Integer | |
-- summed = sum $ (,) x'' y'' | |
-- weston | |
-- summed = (+) <$> x'' <*> y'' | |
-- derek | |
summed = fmap sum $ (,) <$> x'' <*> y'' | |
-- wilson | |
summed'' = fmap sum $ pure (,) <*> x'' <*> y'' | |
---- Identity | |
newtype Identity a = Identity a deriving (Eq, Ord, Show) | |
instance Functor Identity where | |
fmap f (Identity a) = Identity (f a) | |
instance Applicative Identity where | |
pure a = Identity a | |
Identity f <*> Identity a = Identity (f a) | |
--- Constant | |
newtype Constant a b = | |
Constant { getConstant :: a } | |
deriving (Eq, Ord, Show) | |
instance Functor (Constant a) where | |
fmap f (Constant a) = Constant { getConstant = a } | |
instance Monoid a => Applicative (Constant a) where | |
pure a = Constant { getConstant = mempty } | |
Constant f <*> Constant a = Constant $ mappend f a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment