简体   繁体   English

如何为用户定义的类型实现Eq类型类?

[英]How is Eq typeclass implemented for user defined types?

For some user defined type such as the below how does the implementation of the Eq typeclass work? 对于某些用户定义的类型,如下所示,Eq类型类的实现如何工作? Its simple to write an implementation for things like Int or Float. 为Int或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: 例如,如果您将代码放在一个文件中并使用-ddump-deriv运行ghc-ddump-deriv这就是您所获得的:

==================== 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM