計算機科学のブログ

型の紹介 カスタム型の作成 レコード構文、フィールドの値の取り出し、出力、文字列、show関数

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

コード

type FirstName = String

type LastName = String

type MiddleName = String

data Name
  = Name FirstName LastName
  | NameWithMiddleName FirstName MiddleName LastName

showName :: Name -> String
showName (Name fname lname) = lname ++ ", " ++ fname
showName (NameWithMiddleName fname mname lname) =
  lname ++ ", " ++ fname ++ " " ++ mname

data Sex = Male | Female

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

data ABOType = A | B | AB | O

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

data RhType = Pos | Neg

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

data BloodType = BloodType ABOType RhType

showBloodType :: BloodType -> String
showBloodType (BloodType abo rh) = showABOType abo ++ showRhType rh

showAge :: Int -> String
showAge a = show a

showHeight :: Int -> String
showHeight h = show h ++ " in."

showWeight :: Int -> String
showWeight w = show w ++ " lbs."

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

patientSummary :: Patient -> String
patientSummary p =
  take 14 (cycle "*") ++ "\n" ++ "Patient Name: " ++ showName (name p) ++ "\n"
    ++ "Sex: "
    ++ showSex (sex p)
    ++ "\n"
    ++ "Age: "
    ++ showAge (age p)
    ++ "\n"
    ++ "Height: "
    ++ showHeight (height p)
    ++ "\n"
    ++ "Weight: "
    ++ showWeight (weight p)
    ++ "\n"
    ++ "Blood Type: "
    ++ showBloodType (bloodType p)
    ++ "\n"

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

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

入出力結果(Terminal, Zsh)

% runghc sample2.hs
**************
Patient Name: Smith, John
Sex: Male
Age: 46
Height: 72 in.
Weight: 210 lbs.
Blood Type: AB+
%