計算機科学のブログ

型によるプログラミング 直積型と直和型 直積型 レコード構文

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT3(型によるプログラミング)、LESSON 16(直積型と直和型)、16.1(直積型)、クイックチェック 16-1の解答を求めてみる。

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

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 authorName

lesson/src/Lib.hs

module Lib
  ( authorName,
  )
where

authorName :: AuthorName
authorName =
  AuthorName
    { firstName = "Will",
      lastName = "Kurt"
    }

data AuthorName = AuthorName
  { firstName :: String,
    lastName :: String
  }
  deriving (Show)

入出力結果(Terminal, Zsh)

% stack build
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..
[2 of 2] Compiling Main
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/de4304b604e621b4990474780a8e3cc3a4bc2e5a84cb8fe46ca20d9984a0bb04/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/de4304b604e621b4990474780a8e3cc3a4bc2e5a84cb8fe46ca20d9984a0bb04/9.0.2/bin
Registering library for lesson-0.1.0.0..
% stack exec lesson-exe
AuthorName {firstName = "Will", lastName = "Kurt"}
%