計算機科学のブログ

Haskell - コンテキストでの型の操作 - Applicative型クラス:関数をコンテキスト内で使用する - コンテキストでの部分適用に<*>を使用する

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT5(コンテキストでの型の操作)、LESSON 28(Applicative型クラス:関数をコンテキスト内で使用する)、28.2(コンテキストでの部分適用に<*>を使用する)、クイックチェック28-3の解答を求めてみる。

コード

sample3.hs

main :: IO ()
main = do
  mapM_ (\(op, x, y) -> print $ op <$> x <*> y) opxys

ops :: [Integer -> Integer -> Integer]
ops = [(*), div, mod]

xys :: [(Maybe Integer, Maybe Integer)]
xys =
  [ (Nothing, Nothing),
    (Nothing, Just 2),
    (Just 3, Nothing),
    (Just 3, Just 2)
  ]

opxys :: [(Integer -> Integer -> Integer, Maybe Integer, Maybe Integer)]
opxys = concat $ map (\op -> map (\(x, y) -> (op, x, y)) xys) ops

入出力結果(Terminal, Zsh)

% runghc sample3.hs
Nothing
Nothing
Nothing
Just 6
Nothing
Nothing
Nothing
Just 1
Nothing
Nothing
Nothing
Just 1
%