計算機科学のブログ

型によるプログラミング パラメータ化された型 Data.Mapモジュール、キー、lookup関数、Ord

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT3(型によるプログラミング)、LESSON 18(パラメータ化された型)、18.4(練習問題)Q18-2の解答を求めてみる。

lesson/package.yaml

name:                lesson
version:             0.1.0.0
github:              "githubuser/lesson"
license:             BSD3
author:              "Author name here"
maintainer:          "example@example.com"
copyright:           "2022 Author name here"

extra-source-files:
- README.md
- ChangeLog.md

# Metadata used when publishing your package
# synopsis:            Short description of your package
# category:            Web

# To avoid duplicated efforts in documentation and dealing with the
# complications of embedding Haddock markup inside cabal files, it is
# common to point users to the README.md file.
description:         Please see the README on GitHub at <https://github.com/githubuser/lesson#readme>

dependencies:
- base >= 4.7 && < 5
- containers

library:
  source-dirs: src

executables:
  lesson-exe:
    main:                Main.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - lesson

tests:
  lesson-test:
    main:                Spec.hs
    source-dirs:         test
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - lesson

コード

lesson/app/Main.hs

module Main where

import Lib

main :: IO ()
main = do
  print allOrgans
  print organCatalog
  print organInventory
  print lookuped

lesson/src/Lib.hs

module Lib where

import qualified Data.Map as Map

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

allOrgans = [Heart .. Spleen]

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

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

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

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

catalogValues :: [Organ]
catalogValues = map snd $ Map.toList organCatalog

countOrgan :: [(Organ, Int)]
countOrgan =
  map
    ( ( \organ ->
          ( organ,
            length $ filter (== organ) catalogValues
          )
      )
        . snd
    )
    $ Map.toList organCatalog

organInventory :: Map.Map Organ Int
organInventory = Map.fromList countOrgan

lookuped :: [Maybe Int]
lookuped =
  map
    (\organ -> Map.lookup organ organInventory)
    allOrgans

入出力結果(Terminal, Zsh)

% stack exec lesson-exe
[Heart,Brain,Kidney,Spleen]
fromList [(2,Heart),(7,Heart),(13,Brain),(14,Spleen),(21,Spleen),(24,Kidney)]
fromList [(Heart,2),(Brain,1),(Kidney,1),(Spleen,2)]
[Just 2,Just 1,Just 1,Just 2]
%