計算機科学のブログ

型の紹介 カスタム型の作成 レコード構文を使用する フィールド

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT2(型の紹介)、LESSON 12(カスタム型の作成)、12.3(レコード構文を使用する)、クイックチェック 12-3の解答を求めてみる。

コード

lesson/app/Main.hs

module Main where

import Lib ()

main :: IO ()
main = return ()

lesson/src/Lib.hs

module Lib () where

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

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
  deriving (Show)

data Sex = Male | Female
  deriving (Show)

data ABOType = A | B | AB | O
  deriving (Show)

data RhType = Pos | Neg
  deriving (Show)

data BloodType = BloodType ABOType RhType
  deriving (Show)

入出力結果(Terminal, Zsh)

% stack ghci
Using main module: 1. Package `lesson' component lesson:exe:lesson-exe with main-is file: /Users/…/lesson/app/Main.hs
The following GHC options are incompatible with GHCi and have not been passed to it: -threaded
Configuring GHCi with the following packages: lesson

* * * * * * * *

Warning: Multiple files use the same module name:
         * Paths_lesson found at the following paths
           * /Users/…/lesson/.stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/autogen/Paths_lesson.hs (lesson:lib)
           * /Users/…/lesson/.stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/lesson-exe/autogen/Paths_lesson.hs (lesson:exe:lesson-exe)
* * * * * * * *

GHCi, version 9.0.2: 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 /Users/…/.ghc/ghci.conf
[1 of 3] Compiling Lib              ( /Users/…/lesson/src/Lib.hs, interpreted )
[2 of 3] Compiling Main             ( /Users/…/lesson/app/Main.hs, interpreted )
[3 of 3] Compiling Paths_lesson     ( /Users/…/lesson/.stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/autogen/Paths_lesson.hs, interpreted )
Ok, three modules loaded.
Loaded GHCi configuration from /private/var/folders/wj/52wjq8dn0fj1qltsnx3xxpnh0000gn/T/haskell-stack-ghci/4e370d31/ghci-script
*Main Lib Paths_lesson
λ> :load Lib
[1 of 1] Compiling Lib              ( /Users/…/lesson/src/Lib.hs, interpreted )
Ok, one module loaded.
(0.03 secs,)
*Lib
λ> name jackieSmith 
Name "Jackie" "Smith"
it :: Name
(0.02 secs, 520,248 bytes)
*Lib
λ> :quit
Leaving GHCi.
%