pure は良きにはからって型を合わせてくれます。

Applicative functorsに pure という関数が登場します。
その役目は Monad の return に似ています。
まず、 return の復習、というより良く分かっていませんでした・・・Orz

class Monad m where
  (>>=) :: m a -> (a -> m b) -> m b
  (>>) :: m a -> m b -> m b
  return :: a -> m a
  fail :: String -> m a
  	-- Defined in GHC.Base
instance Monad Maybe -- Defined in Data.Maybe
instance Monad [] -- Defined in GHC.Base
instance Monad IO -- Defined in GHC.Base

return は引数をMonadにくるんで返す関数です。
Monad Maybe、Monad []、Monad IO のインスタンスがありますのでオブジェクト指向ポリモーフィズムのような動作をします。

-- 出力する型を Maybe Monad に指定すると Maybe Monad を返す動作をします。
> :t return "hello" ::Maybe String
return "hello" ::Maybe String :: Maybe String

-- 出力する型を List Monad に指定すると List Monad を返す。
> :t return "hello" ::[] String
return "hello" ::[] String :: [String]

-- 出力する型を IO Monad に指定すると IO Monad を返す。
> :t return "hello" ::IO String
return "hello" ::IO String :: IO String
  • pure
ghci> :m + Control.Applicative
ghci> :i Applicative

class (Functor f) => Applicative f where
  pure :: a -> f a
  (<*>) :: f (a -> b) -> f a -> f b
  (*>) :: f a -> f b -> f b
  (<*) :: f a -> f b -> f a
  	-- Defined in Control.Applicative
instance Applicative [] -- Defined in Control.Applicative
instance Applicative ZipList -- Defined in Control.Applicative
instance (Monad m) => Applicative (WrappedMonad m)
  -- Defined in Control.Applicative
instance Applicative Maybe -- Defined in Control.Applicative
instance Applicative IO -- Defined in Control.Applicative
instance Applicative ((->) a) -- Defined in Control.Applicative
  • pure は引数を指定された型に変換して返します。
> :t pure (100::Int)
pure (100::Int) :: (Applicative f) => f Int

> pure (100::Int) ::[Int]      -- => [100]
> pure (100::Int) ::Maybe Int  -- => Just 100
> pure (100::Int) ::IO Int     -- => 100
  • pure は良きにはからって型を合わせてくれます。
> pure 100 == [100]    -- => True
> pure 100 == Just 100 -- => True
> pure 100 == Nothing  -- => False


>  pure (+3) <*> Just 10                  -- => Just 13

>  pure (+3) <*> (return 10)::IO Integer  -- => 13

> :t pure (+3) <*> (return 10)::IO Integer
pure (+3) <*> (return 10)::IO Integer :: IO Integer

>  pure (+3) <*> [10,11,20]               -- => [13,14,23]

> (+3) `fmap` [10,11,20]                 -- => [13,14,23]
> (+3) `fmap` Just 10                    -- => Just 13

> (+3) `map` [10,11,20]                  -- => [13,14,23]