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
show :: a -> String
(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 of Show
) this is a function that takes an a
and returns a string
An instance for this would look like this
instance Show SomeType where
show SomeConstructor = "SomeConstructor"
Which means
SomeType
satisfies the constraint Show
, and I'll show you how by providing an implementation of show
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.
class
andinstance
. I think it is a bit unfortunate that the nomenclature of Haskell is quite similar to that of most imperative programming languages, but actually has some very different meanings. – Willem Van Onsem