如何在Haskell中正确实例化类? [英] How to properly instantiate classes in Haskell?

查看:136
本文介绍了如何在Haskell中正确实例化类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图创建一个可以派生出不同类型的基类。以下是什么错误?

  class(Eq a)=> MyClass a 

数据Alpha = Alpha
实例MyClass Alpha其中
Alpha == Alpha = True

我得到错误:

  test.hs:5:10:`= ='不是'MyClass'类的(可见)方法
失败,模块加载:无。


解决方案

你必须明确地让Alpha成为Eq的一个实例。这将工作:

pre $ code数据Alpha = Alpha
实例Eq Alpha其中
Alpha == Alpha = True
实例MyClass Alpha


Trying to create a base class from which I can derive different types. What's wrong with the following?

class (Eq a) => MyClass a 

data Alpha = Alpha
instance MyClass Alpha where
    Alpha == Alpha = True

I get the error:

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

解决方案

You have to make Alpha an instance of Eq explicitly. This will work:

data Alpha = Alpha
instance Eq Alpha where
    Alpha == Alpha = True
instance MyClass Alpha

这篇关于如何在Haskell中正确实例化类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆