型によるプログラミング Maybe型:欠損値に対処する JustとNothing
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT3(型によるプログラミング)、LESSON19(Maybe型:欠損値に対処する)、19.6(練習問題)Q19-1の解答を求めてみる。
コード
import Data.Map as Map
import Data.Maybe (isNothing)
data Organ = Heart | Brain deriving (Show)
getDrawerContents :: [Int] -> Map.Map Int Organ -> [Maybe Organ]
getDrawerContents ids catalog =
Prelude.map (\id -> Map.lookup id catalog) ids
emptyDrawers :: [Maybe Organ] -> Int
emptyDrawers [] = 0
emptyDrawers (Nothing : xs) = 1 + emptyDrawers xs
emptyDrawers (_ : xs) = emptyDrawers xs
contents :: [Maybe Organ]
contents = [Just Heart, Nothing, Just Brain, Just Brain, Nothing]
main = do
print $ emptyDrawers []
print $ emptyDrawers [Nothing]
print $ emptyDrawers [Just Heart]
print $ emptyDrawers contents
入出力結果(Terminal, Zsh)
% runghc sample1.hs
0
1
0
2
%