Skip to content

Instantly share code, notes, and snippets.

@monzou
Created June 30, 2012 13:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monzou/3023764 to your computer and use it in GitHub Desktop.
Save monzou/3023764 to your computer and use it in GitHub Desktop.
import Control.Applicative
-- fmap : (a -> b) -> f a -> f b
-- fmap は関数とファクター値を引数にとって, 関数をファンクター値の中の値に適用
class Functor f where
fmap :: (a -> b) -> f a -> f b
-- <*> : f (a -> b) -> f a -> f b (f is Fanctor)
-- <*> は関数の入っているファンクター値と値の入っているファンクター値を引数にとって, ひとつ目のファンクターの中身の関数をふたつ目のファンクターの中身に適用
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> something = fmap f something
instance Applicative [] where
pure x = [x]
fs <*> xs = [ f x | f <- fs, x <- xs ]
main = do
print $ pure (+) <*> Just 3 <*> Just 5 -- Just 8
print $ pure (+) <*> Just 3 <*> Nothing -- Nothing
print $ [ (+), (*) ] <*> [ 1, 2 ] <*> [ 3, 4 ] -- [ (1+), (2+), (1*), (2*) ] <*> [ 3, 4 ] ...
print $ (++) <$> Just "hello" <*> Just "world" -- Just helloworld (<$> は fmap の中置関数)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment