Haskell Cheat Sheet Page 4

ADVERTISEMENT

same accessor function for values of the same type,
Because seven of these operations are so com-
but that can be dangerous if the accessor is not used
mon, Haskell provides the
keyword
by all constructors. Consider this rather contrived
which will automatically implement the typeclass
Some literature refers to this practice as type pun-
example:
on the associated type. The seven supported type-
ning.
classes are:
,
,
,
,
,
, and
.
Type Variables
Declaring so-called polymorphic
Two forms of
are possible. The first is
data types is as easy as adding type variables in
used when a type only derives one class:
the declaration:
This declares a type
with two constructors,
If
is called with a
value, a runtime
and
. The
constructor can take
error will occur.
an argument of any type, which is represented by
The second is used when multiple classes are de-
Finally, as explained elsewhere, these names
the type variable
above.
rived:
can be used for pattern matching, argument cap-
We can also mix type variables and specific
ture and “updating.”
types in constructors:
Class Constraints
Data types can be declared
with class constraints on the type variables, but
Above, the
constructor can take a value of
this practice is generally discouraged. It is gener-
It is a syntax error to specify
for any other
any type and an
value.
ally better to hide the “raw” data constructors us-
classes besides the six given above.
ing the module system and instead export “smart”
Record Syntax
Constructor arguments can be
constructors which apply appropriate constraints.
declared either positionally, as above, or using
In any case, the syntax used is:
record syntax, which gives a name to each argu-
Deriving
ment. For example, here we declare a
type
See the section on
under the
key-
with names for appropriate arguments:
word on page 4.
This declares a type
which has one
type variable argument. Valid types are those in
the
class.
Do
These names are referred to as selector or accessor
functions and are just that, functions. They must
Deriving
Many types have common operations
The
keyword indicates that the code to follow
start with a lowercase letter or underscore and can-
which are tedious to define yet necessary, such as
will be in a monadic context. Statements are sepa-
not have the same name as another function in
the ability to convert to and from strings, compare
rated by newlines, assignment is indicated by
,
scope. Thus the “ ” prefix on each above. Mul-
for equality, or order in a sequence. These capabil-
and a
form is introduce which does not require
tiple constructors (of the same type) can use the
ities are defined as typeclasses in Haskell.
the
keyword.
c 2009 Justin Bailey.
4

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education