Haskell - コンテキストでの型の操作 - Applicative型クラス:関数をコンテキスト内で使用する - 2つの都市の距離を計算するコマンドラインアプリケーション
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT5(コンテキストでの型の操作)、LESSON 28(Applicative型クラス:関数をコンテキスト内で使用する)、28.1(2つの都市の距離を計算するコマンドラインアプリケーション)、クイックチェック28-1の解答を求めてみる。
コード
sample1.hs
main :: IO ()
main = do
mapM_ (\(n, m) -> print (n, m, addMaybe n m))
[(Nothing, Nothing),
(Nothing, Just 2),
(Just 2, Nothing),
(Just 2, Just 3)]
addMaybe :: Maybe Int -> Maybe Int -> Maybe Int
addMaybe (Just n) (Just m) = Just (n + m)
addMaybe _ _ = Nothing
入出力結果(Terminal, Zsh)
% runghc sample1.hs
(Nothing,Nothing,Nothing)
(Nothing,Just 2,Nothing)
(Just 2,Nothing,Nothing)
(Just 2,Just 3,Just 5)
%