計算機科学のブログ

型によるプログラミング Maybe型 リスト、filter関数

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

コード

import qualified Data.Map as Map

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

organs :: [Organ]
organs = [Heart, Heart, Brain, Spleen, Spleen, Kidney]

ids :: [Int]
ids = [2, 7, 13, 14, 21, 24]

organPairs :: [(Int, Organ)]
organPairs = zip ids organs

organCatalog :: Map.Map Int Organ
organCatalog = Map.fromList organPairs

getDrawerContents :: [Int] -> Map.Map Int Organ -> [Maybe Organ]
getDrawerContents ids catalog =
  let getContents = \id -> Map.lookup id catalog
   in map getContents ids

emptyDrawers :: [Maybe Organ] -> Int
emptyDrawers organs = length (filter (Nothing ==) organs)

drawerContents :: [Maybe Organ]
drawerContents = getDrawerContents [1 .. 100] organCatalog

入出力結果(Terminal, Zsh)

% ghci
GHCi, version 8.10.5: https://www.haskell.org/ghc/  :? for help
macro 'doc' overwrites builtin command.  Use ':def!' to overwrite.
(0.00 secs, 0 bytes)
(0.00 secs, 0 bytes)
Loaded GHCi configuration from /.../.ghc/ghci.conf
Prelude
λ> :load sample1
[1 of 1] Compiling Main             ( sample1.hs, interpreted )
Ok, one module loaded.
(0.10 secs,)
*Main
λ> emptyDrawers drawerContents 
94
it :: Int
(0.02 secs, 86,104 bytes)
*Main
λ> drawerContents 
[Nothing,Just Heart,Nothing,Nothing,Nothing,Nothing,Just Heart,Nothing,Nothing,Nothing,Nothing,Nothing,Just Brain,Just Spleen,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Just Spleen,Nothing,Nothing,Just Kidney,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing]
it :: [Maybe Organ]
(0.01 secs, 686,312 bytes)
*Main
λ> :quit
Leaving GHCi.
%