計算機科学のブログ

型の紹介 型クラスを使用する サイコロ、乱数

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT2(型の紹介)、LESSON 14(型クラスを使用する)、14.10(練習問題)Q14-2の解答を求めてみる。

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
- random

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

p :: Int -> IO ()
p 0 = return ()
p n = do
  s <- roll :: IO FiveSidedDie
  print s
  p (n - 1)

main :: IO ()
main = p 20

lesson/src/Lib.hs

module Lib where

import System.Random (randomRIO)

data FiveSidedDie
  = S1
  | S2
  | S3
  | S4
  | S5
  deriving (Show, Eq, Enum)

class Die a where
  roll :: IO a

instance Die FiveSidedDie where
  roll = do
    n <- randomRIO (fromEnum S1, fromEnum S5)
    return $ toEnum n

入出力結果(Terminal, Zsh)

% stack build          
lesson-0.1.0.0: unregistering (local file changes: app/Main.hs)
lesson> build (lib + exe)
Preprocessing library for lesson-0.1.0.0..
Building library for lesson-0.1.0.0..
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/11bee7f1432551708036aee298c43f57d1e8b1a145053e7d2d3b07e2f4ae638f/9.0.2/lib/x86_64-osx-ghc-9.0.2/lesson-0.1.0.0-9bTA0skkzcAPSU64JpGSw
Installing executable lesson-exe in /Users/…/lesson/.stack-work/install/x86_64-osx/11bee7f1432551708036aee298c43f57d1e8b1a145053e7d2d3b07e2f4ae638f/9.0.2/bin
Registering library for lesson-0.1.0.0..
% stack exec lesson-exe
S3
S2
S1
S2
S2
S2
S1
S5
S1
S1
S5
S4
S1
S2
S2
S4
S3
S5
S1
S1
%