如何在Haskell中正确实例化类?

me2*_*me2 4 haskell typeclass

试图创建一个基类,我可以从中派生出不同的类型.以下是什么问题?

class (Eq a) => MyClass a 

data Alpha = Alpha
instance MyClass Alpha where
    Alpha == Alpha = True
Run Code Online (Sandbox Code Playgroud)

我收到错误:

test.hs:5:10: `==' is not a (visible) method of class `MyClass'
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)

sep*_*p2k 8

你必须明确地使Alpha成为Eq的一个实例.这将有效:

data Alpha = Alpha
instance Eq Alpha where
    Alpha == Alpha = True
instance MyClass Alpha
Run Code Online (Sandbox Code Playgroud)

  • 正确,但你应该更像是"如果想要实例化MyClass,它首先需要实例化Eq"而不是继承. (3认同)