計算機科学のブログ

型の紹介 - カスタム型の作成 - ヘルパー関数

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

コード

sample.hs

main :: IO ()
main = do
  putStrLn $ patientSummary johnDoe
  putStrLn $ patientSummary jackieSmith

type FirstName = String

type LastName = String

type MiddleName = String

data Name
  = Name FirstName LastName
  | NameWithMiddleName FirstName MiddleName LastName

showName :: Name -> String
showName (Name f l) = l ++ ", " ++ f
showName (NameWithMiddleName f m l) = l ++ ", " ++ m ++ ", " ++ f

data Sex = Male | Female

showSex :: Sex -> String
showSex Male = "Male"
showSex Female = "Female"

data RhType = Pos | Neg

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

data ABOType = A | B | AB | O

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

data BloodType = BloodType ABOType RhType

showBlood :: BloodType -> String
showBlood (BloodType abo rh) = showABO abo ++ showRh rh

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

patientSummary :: Patient -> String
patientSummary p =
  replicate 15 '*'
    ++ "\n"
    ++ "Patient Name: "
    ++ showName (name p)
    ++ "\n"
    ++ "Sex: "
    ++ showSex (sex p)
    ++ "\n"
    ++ "Age: "
    ++ show (age p)
    ++ "\n"
    ++ "Height: "
    ++ show (height p)
    ++ " in."
    ++ "\n"
    ++ "Weight: "
    ++ show (weight p)
    ++ " lbs."
    ++ "\n"
    ++ "Blood Type: "
    ++ showBlood (bloodType p)

johnDoe :: Patient
johnDoe =
  Patient
    { name = Name "John" "Doe",
      sex = Male,
      age = 30,
      height = 74,
      weight = 200,
      bloodType = BloodType AB Pos
    }

jackieSmith :: Patient
jackieSmith =
  Patient
    { name = Name "Jackie" "Smith",
      age = 43,
      sex = Female,
      height = 62,
      weight = 115,
      bloodType = BloodType O Neg
    }

入出力結果(Terminal, Zsh)

% runghc sample.hs
***************
Patient Name: Doe, John
Sex: Male
Age: 30
Height: 74 in.
Weight: 200 lbs.
Blood Type: AB+
***************
Patient Name: Smith, Jackie
Sex: Female
Age: 43
Height: 62 in.
Weight: 115 lbs.
Blood Type: O-
%