Haskell Cheat Sheet Page 3

ADVERTISEMENT

Data
So-called algebraic data types can be declared as fol-
Notice that the declaration only gives the type
lows:
Guards
Guards, or conditional matches, can be
signature of the function—no implementation is
used in cases just like function definitions. The only
given here (with some exceptions, see
“Defaults”
difference is the use of the
instead of . Here
on page 3). Continuing, we can define several in-
is the type’s name.
and
is a simple function which does a case-insensitive
stances:
are values of the type and are called con-
string match:
structors. Multiple constructors are separated with
the ‘ ’ character. Note that type and constructor
names must start with a capital letter. It is a syntax
error otherwise.
Constructors with Arguments
The type above
Evaluating
gives:
is not very interesting except as an enumeration.
Constructors that take arguments can be declared,
allowing more information to be stored:
Class
While
gives:
A Haskell function is defined to work on a certain
type or set of types and cannot be defined more
Notice that the arguments for each constructor are
than once. Most languages support the idea of
type names, not constructors. That means this kind
“overloading”, where a function can have different
of declaration is illegal:
behavior depending on the type of its arguments.
Defaults
Default implementations can be given
for functions in a class. These are useful when cer-
Haskell accomplishes overloading through
and
declarations. A
defines one
tain functions can be defined in terms of others in
instead, the
type must be used:
or more functions that can be applied to any types
the class. A default is defined by giving a body to
which are members (i.e., instances) of that class. A
one of the member functions. The canonical exam-
class is analogous to an interface in Java or C#, and
ple is
, which defines
(not equal) in terms of
. :
instances to a concrete implementation of the inter-
Type and Constructor Names
Type and con-
face.
structor names can be the same, because they will
A class must be declared with one or more type
never be used in a place that would cause confu-
variables. Technically, Haskell 98 only allows one
sion. For example:
type variable, but most implementations of Haskell
support so-called multi-parameter type classes, which
allow more than one type variable.
Recursive definitions can be created, but an
which declares a type named
with two con-
We can define a class which supplies a flavor for
declaration must always implement at
structors,
and
. Using this type in a
a given type:
least one class member.
function makes the difference clear:
c 2009 Justin Bailey.
3

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education