ITコンサルの日常

ITコンサル会社に勤務する普通のITエンジニアの日常です。

代数的データ型とdata宣言

ふつうのHaskellプログラミング p224

data Anchor = A String String

みたいなことをやって、Stringのフィールドを二つ持つAnchor型を定義できるってことらしい。
Javaで言えば、

class Anchor
{
  private String s1;
  private String s2;
}

みたいなところでしょう。きっと。


で、早速サンプルを書いてみる。

data Anchor = A String String

href :: Anchor
href = A "http://example.com/" "Support Page"

main = print href

が、コンパイルエラーとなりました。

data3.hs:6:7:
    No instance for (Show Anchor)
      arising from a use of `print' at data3.hs:6:7-16
    Possible fix: add an instance declaration for (Show Anchor)
    In the expression: print href
    In the definition of `main': main = print href

想像するに、Anchor型はShow可能じゃない。みたいなエラーかと思いました。
リファレンスのprintを参照すると、型が「print :: Show a => a -> IO ()」なので、print関数に渡す引数はShow型であることが必須なわけです。


じゃあどうすればいいかというと、もう少し後ろのページ(p242)にinstance宣言ってのがあって、これを使うとAnchor型にShow型を実装(?)でき、解決します。

data Anchor = A String String
instance Show Anchor where
    show (A url label) = url ++ " " ++ label

href :: Anchor
href = A "http://example.com/" "Support Page"

main = print href

結果はこう。

http://example.com/ Support Page

というわけで、無事実行できました。