計算機科学のブログ

型の紹介 型クラスを使用する Showを実装する

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT2(型の紹介)、LESSON 14(型クラスを使用する)、14.2(Showを実装する)のクイックチェック14-1の解答を求めてみる。

コード

data SixSideDie = S1 | S2 | S3 | S4 | S5 | S6

instance Show SixSideDie where
    show S1 = "I"
    show S2 = "II"
    show S3 = "III"
    show S4 = "IV"
    show S5 = "V"
    show S6 = "VI"

sides :: [SixSideDie]
sides = [S1, S2, S3, S4, S5, S6]

入出力結果(Terminal, Zsh)

% ghci
GHCi, version 8.10.4: 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 sample01.hs 
[1 of 1] Compiling Main             ( sample01.hs, interpreted )
Ok, one module loaded.
(0.01 secs,)
*Main
λ> show sides
"[I,II,III,IV,V,VI]"
it :: String
(0.04 secs, 79,800 bytes)
*Main
λ> sides
[I,II,III,IV,V,VI]
it :: [SixSideDie]
(0.00 secs, 73,880 bytes)
*Main
λ> map show sides
["I","II","III","IV","V","VI"]
it :: [String]
(0.00 secs, 83,592 bytes)
*Main
λ> :quit
Leaving GHCi.
%