Eq类型类是如何为用户定义的类型实现的? [英] How is Eq typeclass implemented for user defined types?

查看:86
本文介绍了Eq类型类是如何为用户定义的类型实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一些用户定义的类型,例如下面的Eq类型类的实现是如何工作的?它很容易编写一个像Int或Float这样的实现。但是,对于所有用户类型来说,它是如何完成的,因为它需要对每个可能的值构造函数进行模式匹配等操作。

  data Person = Person {firstName :: String 
, lastName :: String
,age :: Int
}派生(Eq)


解决方案

它与每个可能的值构造函数匹配,就像你说的一样!例如,如果你把你的代码放在一个文件中,并用 -ddump-deriv 运行 ghc ,这里是你得到的:

  ====================派生实例=== ================= 
派生实例:
实例GHC.Classes.Eq Main.Person其中
GHC.Classes。==
(Main.Person a1_alh a2_ali a3_alj)
(Main.Person b1_alk b2_all b3_alm)
=((((a1_alh GHC.Classes。== b1_alk))
GHC.Classes。& amp ;&((a2_ali GHC.Classes。== b2_all)))
GHC.Classes。&&((a3_alj GHC.Classes。== b3_alm)))
GHC.Classes./ = a_aln b_alo
= GHC.Classes.not((GHC.Classes。==)a_aln b_alo)


For some user defined type such as the below how does the implementation of the Eq typeclass work? Its simple to write an implementation for things like Int or Float. But how is the catchall for all user types done since it would need to do things like pattern match against every possible value constructor? I'm not aware of any syntax to do this.

data Person = Person { firstName :: String
                     , lastName :: String
                     , age :: Int
                     } deriving (Eq)

解决方案

It pattern matches against every possible value constructor, just like you said! For example, if you put your code in a file and run ghc with -ddump-deriv, here's what you get:

==================== Derived instances ====================
Derived instances:
  instance GHC.Classes.Eq Main.Person where
    GHC.Classes.==
      (Main.Person a1_alh a2_ali a3_alj)
      (Main.Person b1_alk b2_all b3_alm)
      = ((((a1_alh GHC.Classes.== b1_alk))
          GHC.Classes.&& ((a2_ali GHC.Classes.== b2_all)))
         GHC.Classes.&& ((a3_alj GHC.Classes.== b3_alm)))
    GHC.Classes./= a_aln b_alo
      = GHC.Classes.not ((GHC.Classes.==) a_aln b_alo)

这篇关于Eq类型类是如何为用户定义的类型实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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