型によるプログラミング パラメータ化された型 Map、キー、Ordクラス
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT3(型によるプログラミング)、LESSON 18(パラメータ化された型)、18.4(練習問題)Q18-2の解答を求めてみる。
コード
import qualified Data.Map as Map
data Organ = Heart | Brain | Kidney | Spleen deriving (Show, Eq, Ord)
ids :: [Int]
ids = [2, 7, 13, 14, 21, 24]
organs :: [Organ]
organs = [Heart, Heart, Brain, Spleen, Spleen, Kidney]
organPairs :: [(Int, Organ)]
organPairs = zip ids organs
organCatalog :: Map.Map Int Organ
organCatalog = Map.fromList organPairs
vals :: [Organ]
vals = map snd (Map.toList organCatalog)
organCount :: Organ -> Int
organCount organ = length (filter (== organ) vals)
organCounts :: [Int]
organCounts = map organCount vals
organInventory :: Map.Map Organ Int
organInventory = Map.fromList (zip vals organCounts)
入出力結果(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 sample2
[1 of 1] Compiling Main ( sample2.hs, interpreted )
Ok, one module loaded.
(0.28 secs,)
*Main
λ> organInventory
fromList [(Heart,2),(Brain,1),(Kidney,1),(Spleen,2)]
it :: Map.Map Organ Int
(0.03 secs, 108,824 bytes)
*Main
λ> organCatalog
fromList [(2,Heart),(7,Heart),(13,Brain),(14,Spleen),(21,Spleen),(24,Kidney)]
it :: Map.Map Int Organ
(0.01 secs, 120,720 bytes)
*Main
λ> Map.lookup Heart organInventory
Just 2
it :: Maybe Int
(0.02 secs, 71,304 bytes)
*Main
λ> Map.lookup Brain organInventory
Just 1
it :: Maybe Int
(0.01 secs, 63,720 bytes)
*Main
λ> :quit
Leaving GHCi.
%