Applicativeは全ての引数が独立に計算される
pros
引数を独立に、並列に計算できる
cons
引数同士で依存が出来ない
e.g. 前の引数の結果を、後続の引数は参照できない
Monadを使おう
Applicativeは各引数のコンテキストが独立して評価される
Applicative版の
if
のような関数を定義する
refhscond :: Applicative f => f Bool -> f a -> f a -> f a
cond fb ft fe = pure cond' <*> fb <*> ft <*> fe
where
cond' b t e = if b then t else e
関数 cond
は、ちょうどそのサブ関数の cond'
のApplicative版
Identity
に対して使用した場合
hsrunIdentity $ cond (pure True) (pure 1) (pure 2) -- 結果: 1
Identity
は単に値をラップするだけのコンテキスト
この場合、 pure
や <*>
は通常の関数適用と同じ
従って、結果は Identity 1
となる
Maybe
に対して使用した場合
hscond (Just True) (Just 1) Nothing -- 結果: Nothing
第1引数が True
なのに、第3引数が返ってきてるように見える
各引数が独立に評価された後に、 cond
に適用される
例がやや恣意的では?

単純に、引数に Nothing
があれば、結果も Nothing
になるというだけ
いや、でもそういうものなのか?わからなくなってきた

>このように、Applicative は逐次的にコンテナを連結できます。ただし、それぞれのコンテナは独立した計算を実行します。
> Applicative にできないことは、前のコンテナの計算結果を用いて、後のコンテナが振る舞いを変えることです。