From my understanding, there are 4 "types" in Haskell:
- Algebraic data type with
data Data type constructors (what's after the=in thedatatypes; not types technically, I don't think)- Type alias with
type - Typeclasses with
class - Type instances with
instance
The questions are:
- If there are more kinds of types in Haskell. If so, what there relations are.
- What the difference is between a
datatype and aclasstypeclass. They seem similar, though obviously they have some different features. Same with (3). - What the difference is between a
datatype and ainstancetypeclass instance.
I am new to Haskell.
dataandnewtypeintroduce new types (or type constructors actually -Maybeisn't a type, butMaybe ais a type for anyathat is a type).A
datadeclaration introduces both a new type (what's left of the=) and a way to represent data of that type (what's right of the=).So for example, if you have a data declaration like this:
Then you have introduced a new type called
SomeType, and a way to construct values ofSomeType, namely the constructorSomeConstructor(which incidentally doesn't have any parameters, so is the the only value inhabiting this type).A typeclass doesn't do either of these things (and neither does an
instance). A typeclass introduces a constraint and a bunch of polymorphic functions that should be available if that constraint is met. Aninstanceis basically saying "this type meets this constraint" by providing an implementation for these functions. So aclassisn't really introducing new types, it's just a way to provide ad-hoc polymorphism for existing types.For instance, the
Showtypeclass is roughly this:(Note that the actual
Showclass inPreludedoesn't quite look like this)shownow has the typeShow a => a -> String, which you can read asAn instance for this would look like this
Which means
That's roughly the gist of it. There are language extensions that allow somewhat more involved things to happen with type classes and instances, but you don't need to worry about that for now.