2010年07月09日 金曜日
■ [文法]応用文法 (dup、swap)
import Control.Applicative import Control.Arrow dup1 x = (x, x) -- 関数モナドを使えばおk... dup2 = do f <- (,) g <- f return g -- dup2をbindで書き換え... dup3 = (,) >>= (>>= return) -- カコワル... dup4 = (,) <$> id <*> id swap1 (x, y) = (y, x) swap2 = uncurry (flip (,)) swap3 = snd &&& fst
結果は...
$> dup1 5 (5,5) $> dup2 5 (5,5) $> dup3 5 (5,5) $> dup4 5 (5,5) $> swap1 (1, -1) (-1,1) $> swap2 (1, -1) (-1,1) $> swap3 (1, -1) (-1,1)
■ [文法]応用文法 (Control.Applicative)
...の簡単な使い方...
関数では<*>の数だけ入力のコピーを作る感じ...
import Control.Applicative -- 例えば、3引数関数の2番目と3番目の引数に他の関数を適用して渡したい場合... functionTest1 = (,,) <$> id <*> (+ 2) <*> (* 3) -- $> functionTest1 4 -- (4,6,12) -- 比較演算子とかに使える... functionTest2 = (&&) <$> (0 <) <*> (< 100) -- $> functionTest2 100 -- False -- (0.functionTest2 99 -- True -- 関数以外は普通な感じ... maybeTest1 = (+) <$> Just 2 <*> Just 3 maybeTest2 = (+) <$> Nothing <*> Just 3 -- $> maybeTest1 -- Just 5 -- $> maybeTest2 -- Nothing listTest1 = (+) <$> [1,2] <*> [3,4] listTest2 = (+) <$> [] <*> [3,4] -- $> listTest1 -- [4,5,5,6] -- $> listTest2 -- [] ioTest1 = (++) <$> getLine <*> getLine -- $> ioTest1 -- 12 -- 34 -- "1234"
swap = snd &&& fst