klequis / zz-haskell-notebook

Notes from learning Haskell
1 stars 0 forks source link

Type class #27

Open klequis opened 2 years ago

klequis commented 2 years ago

A type class is a set of operations defined with respect to a polymorphic type.

When a type has an instance of a type class, values of that type can be used in the standard operations defined for that type class. In Haskell, type classes are unique pairings of a class and a concrete instance. This means that if a given type a has an instance of Eq, it has only one instance of Eq.

Notes

  1. Types are not members of a type class.
  2. Instead, a type has an instance of one or more type classes.
  3. Instances of type classes add functionality (i.e., operators & functions) to types

From the book

A type class is a means of expressing faculties or interfaces that multiple datatypes may have in common. This enables us to write code exclusively in terms of those commonalities without repeating ourselves for each instance. Just as one may sum values of type Int, Integer, Float, Double, and Rational, we can avoid having different +, *, -, negate, etc. functions for each type by unifying them into a single type class. Importantly, these can then be used with all types that have a Num instance. Thus, a type class provides us a means to write code in terms of those operators and have our functions be compatible with all types that have instances of that type class, whether they already exist or are yet to be invented (by you, perhaps).

klequis commented 2 years ago
klequis commented 2 years ago

p. 169 - When you use a value that has an instance of the Eq type class, you are "implementing" the Eq type class.

klequis commented 2 years ago

Type Classes from "Get Programming with Haskell"

klequis commented 2 years ago

Type Classes from A Gentle Introduction to Haskell: Classes

Type classes allow use to declare which types are instances of which class, and to provide definitions of the overloaded operations associated with a class.

klequis commented 2 years ago

Has many comments that s/b combined into something cohesive.

klequis commented 2 years ago

Type classes have 'laws' or rules that most be satisfied. These rules are not enforced by Haskell.

E.g.,