From my understanding, there are 4 "types" in Haskell:
data
=
in the data
types; not types technically, I don't think)type
class
instance
The questions are:
data
type and a class
typeclass. They seem similar, though obviously they have some different features. Same with (3).data
type and a instance
typeclass instance.I am new to Haskell.
data
and newtype
introduce new types (or type constructors actually - Maybe
isn't a type, but Maybe a
is a type for any a
that is a type).
A data
declaration 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:
data SomeType = SomeConstructor
Then you have introduced a new type called SomeType
, and a way to construct values of SomeType
, namely the constructor SomeConstructor
(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. An instance
is basically saying "this type meets this constraint" by providing an implementation for these functions. So a class
isn't really introducing new types, it's just a way to provide ad-hoc polymorphism for existing types.
For instance, the Show
typeclass is roughly this:
class Show a where -- a is an instance of Show if
show :: a -> String -- it has a function called show with this signature
(Note that the actual Show
class in Prelude
doesn't quite look like this)
show
now has the type Show a => a -> String
, which you can read as
for all a, if they meet the constraint
Show
(or alternatively, if they are an instance ofShow
) this is a function that takes ana
and returns a string
An instance for this would look like this
instance Show SomeType where
show SomeConstructor = "SomeConstructor"
Which means
SomeType
satisfies the constraintShow
, and I'll show you how by providing an implementation ofshow
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.