計算機科学のブログ

型の紹介 型クラスを使用する サイコロに有用なメソッドの定義、スーパークラス、インスタンス化

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

コード

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

class Die a where
    roll :: Int -> a

instance Die FiveSideDie where
  roll n = toEnum (mod n 5)

入出力結果(Terminal, Zsh)

% ghci
GHCi, version 8.10.5: 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 /.../.ghc/ghci.conf
Prelude
λ> :load sample2
[1 of 1] Compiling Main             ( sample2.hs, interpreted )
Ok, one module loaded.
(0.05 secs,)
*Main
λ> S1 == S2
False
it :: Bool
(0.01 secs, 66,032 bytes)
*Main
λ> S1 /= S2
True
it :: Bool
(0.00 secs, 62,040 bytes)
*Main
λ> S1 < S2
True
it :: Bool
(0.00 secs, 61,776 bytes)
*Main
λ> S1 > S2
False
it :: Bool
(0.00 secs, 62,400 bytes)
*Main
λ> map roll [1..10]

<interactive>:6:1: error:
    • Ambiguous type variable ‘b0’ arising from a use of ‘print’
      prevents the constraint ‘(Show b0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘b0’ should be.
      These potential instances exist:
        instance Show Ordering -- Defined in ‘GHC.Show’
        instance Show Integer -- Defined in ‘GHC.Show’
        instance [safe] Show FiveSideDie -- Defined at sample2.hs:1:68
        ...plus 23 others
        ...plus 13 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In a stmt of an interactive GHCi command: print it
(0.01 secs,)
*Main
λ> map roll [1..10] :: [FiveSideDie]
[S2,S3,S4,S5,S1,S2,S3,S4,S5,S1]
it :: [FiveSideDie]
(0.00 secs, 88,488 bytes)
*Main
λ> :quit
Leaving GHCi.
%