Applicative型クラス
pureを実装した型クラス
定義
code:purs(hs)
class Apply f <= Applicative f where
pure :: forall a. a -> f a
Haskellの場合
code:hs
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
f aはここでは「ファンクター値」ではなく「アプリカティブ値」と呼ぶ
instance例
Maybe
code:hs
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> something = fmap f something
List
code:hs
instance Applicative [] where
Either
code:hs
instance Applicative Either a where
pure = Right
IO
code:hs
instance Applicative IO where
pure = return
a <*> b = do
f <- a
x <- b
return (f x)
<*>では↓をやってるんだねmrsekut.icon
code:hs
-- このdo式全体の結果はIO 値
(IO 関数) <*> (IO 値) = do
関数 <- IO 関数
値 <- IO 値
pure (関数 値) -- ←これの結果がIO 値になる
(->) r
関連
参考
Brent さんから Applicative スタイルを習ったのが分かって、微笑ましいです。 ref