Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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)
like image 926
user782220 Avatar asked Oct 21 '13 04:10

user782220


People also ask

How do you define Typeclass in Haskell?

What's a typeclass in Haskell? A typeclass defines a set of methods that is shared across multiple types. For a type to belong to a typeclass, it needs to implement the methods of that typeclass. These implementations are ad-hoc: methods can have different implementations for different types.

How do you use EQ in Haskell?

Eq is used for types that support equality testing. The functions its members implement are == and /=. So if there's an Eq class constraint for a type variable in a function, it uses == or /= somewhere inside its definition.

What are Typeclasses used for and how are they similar to interfaces in Java?

An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. These two looks rather similar: type class limit a type's behavior, while interface limit a class' behavior.

What are Typeclasses used for?

They allow users to define functions using overloaded operations, such as the double function we discussed earlier. They allow users to introduce new collections of overloaded functions, so equality and arithmetic operators are not privileged.


1 Answers

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)
like image 114
Daniel Wagner Avatar answered Oct 17 '22 18:10

Daniel Wagner