クラスメソッドには、あらゆる型変数(定義しようとしているものを除く)の上の 制約を付加することができます。たとえば、
class C a where m :: Show b => a -> bこのようなクラスでは、メソッド m は型 b が Show クラスに属していることを要求します。
A Gentle Introduction to Haskell: Classes
とあるのですが、これのインスタンスを作ろうとするとエラーになります。どうすればよいのでしょうか。
class C a where m :: Show b => a -> b instance C Int where m i = i
test.hs:5:10:
Couldn't match expected type `b' (a rigid variable)
against inferred type `Int'
`b' is bound by the type signature for `m' at test.hs:2:12
In the expression: i
In the definition of `m': m i = i
In the definition for method `m'
{-# OPTIONS -fglasgow-exts #-} import Data.Char class Show b => C a b | b -> a where m :: a -> b instance C Int Int where m i = i instance C Int Char where m i = chr i instance C Int String where m i = show i test = do print (m 1 :: Int) print (m 1 :: Char) print (m 1 :: String) {- ちゃんとerrorになる data Hoge instance C Int Hoge where m = undefined -}
ひとまずこれで動きはしますが、ということでした。
7.6.?Class and instances declarations
うーん。