計算機科学のブログ

Haskell - 型によるプログラミング - Maybe型:欠損値に対処する - Maybe型に対応するmap関数

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT3(型によるプログラミング)、LESSON 19(Maybe型:欠損値に対処する)、19.6(練習問題)、Q19-1の解答を求めてみる。

コード

sample.hs

import Data.Maybe (isNothing)
main :: IO ()
main = do
    mapM_ print contents
    print $ emptyDrawers contents
    mapM_ print nums
    mapM_ print $ maybeMap (* 2) nums

data Organ = Heart | Brain | Kidney | Spleen deriving (Show, Enum)

-- Q19-1
emptyDrawers :: [Maybe Organ] -> Int
emptyDrawers contents = length $ filter isNothing contents

contents :: [Maybe Organ]
contents = [Nothing] ++ map Just [Heart .. Spleen] ++ [Nothing]

-- Q19-2
maybeMap :: (a -> b) -> [Maybe a] -> [Maybe b]
maybeMap _ [] = []
maybeMap func (Nothing:xs) = Nothing:maybeMap func xs
maybeMap func (Just x:xs) = Just (func x):maybeMap func xs

nums :: [Maybe Int]
nums = [Nothing] ++ map Just [-5 .. 5] ++ [Nothing]

入出力結果(Terminal, Zsh)

% runghc sample.hs
Nothing
Just Heart
Just Brain
Just Kidney
Just Spleen
Nothing
2
Nothing
Just (-5)
Just (-4)
Just (-3)
Just (-2)
Just (-1)
Just 0
Just 1
Just 2
Just 3
Just 4
Just 5
Nothing
Nothing
Just (-10)
Just (-8)
Just (-6)
Just (-4)
Just (-2)
Just 0
Just 2
Just 4
Just 6
Just 8
Just 10
Nothing
%