計算機科学のブログ

型の紹介 カスタム型の作成 文字列、出力

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT2(型の紹介)、LESSON 12(カスタム型の作成)、12.5(練習問題)Q12-2の解答を求めてみる。

コード

lesson/app/Main.hs

module Main where

import Lib
  ( johnSmith,
    patientSummary,
  )

main :: IO ()
main = do
  putStrLn $ patientSummary johnSmith

lesson/src/Lib.hs

module Lib
  ( johnSmith,
    patientSummary,
  )
where

johnSmith :: Patient
johnSmith =
  Patient
    { name = Name "John" "Smith",
      age = 46,
      sex = Female,
      height = 72,
      weight = 210,
      bloodType = BloodType AB Pos
    }

data Patient = Patient
  { name :: Name,
    sex :: Sex,
    age :: Int,
    height :: Int,
    weight :: Int,
    bloodType :: BloodType
  }

type FirstName = String

type MiddleName = String

type LastName = String

data Name
  = Name FirstName LastName
  | NameWithMiddle FirstName MiddleName LastName

data Sex = Male | Female

data ABOType = A | B | AB | O

data RhType = Pos | Neg

data BloodType = BloodType ABOType RhType

showName :: Name -> String
showName (Name fname lname) = mconcat [fname, ", ", lname]
showName (NameWithMiddle fname mname lname) =
  mconcat [fname, " ", mname, " ", lname]

showSex :: Sex -> Char
showSex Male = 'M'
showSex Female = 'F'

showBloodType :: BloodType -> String
showBloodType (BloodType abo rh) =
  mconcat
    [ showABO abo,
      showRh rh
    ]

showABO :: ABOType -> String
showABO A = "A"
showABO B = "B"
showABO AB = "AB"
showABO O = "O"

showRh :: RhType -> String
showRh Pos = "+"
showRh Neg = "-"

patientSummary :: Patient -> String
patientSummary patient =
  mconcat
    [ replicate 14 '*',
      "\nPatient Name: ",
      showName $ name patient,
      "\nSex: ",
      [showSex $ sex patient],
      "\nAge: ",
      show $ age patient,
      "\nHeight: ",
      show $ height patient,
      " in.",
      "\nWeight: ",
      show $ weight patient,
      " lbs.",
      "\nBlood Type: ",
      showBloodType $ bloodType patient
    ]

入出力結果(Terminal, Zsh)

% stack build          
lesson-0.1.0.0: unregistering (local file changes: src/Lib.hs)
lesson> build (lib + exe)
Preprocessing library for lesson-0.1.0.0..
Building library for lesson-0.1.0.0..
[2 of 2] Compiling Lib
Preprocessing executable 'lesson-exe' for lesson-0.1.0.0..
Building executable 'lesson-exe' for lesson-0.1.0.0..
Linking .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/lesson-exe/lesson-exe ...
lesson> copy/register
Installing library in /Users/…/lesson/.stack-work/install/x86_64-osx/58a4c4d937f77ed7ad33a3d831dc078cdd38bc2500aef58d99dd5ff42214f933/9.0.2/lib/x86_64-osx-ghc-9.0.2/lesson-0.1.0.0-CIOIkpTgcfQI9akDJnwnSd
Installing executable lesson-exe in /Users/…/lesson/.stack-work/install/x86_64-osx/58a4c4d937f77ed7ad33a3d831dc078cdd38bc2500aef58d99dd5ff42214f933/9.0.2/bin
Registering library for lesson-0.1.0.0..
% stack exec lesson-exe
**************
Patient Name: John, Smith
Sex: F
Age: 46
Height: 72 in.
Weight: 210 lbs.
Blood Type: AB+
%