Haskell Cheat Sheet Page 8

ADVERTISEMENT

Newtype
Finally, it should be noted that any
clause which can be attached to a
declaration
While
introduces new values and
just
can also be used when declaring a
.
creates synonyms,
falls somewhere be-
Because
is just a synonym, it cannot declare
tween. The syntax for
is quite restricted—
multiple constructors the way
can. Type vari-
Return
only one constructor can be defined, and that con-
ables can be used, but there cannot be more than
structor can only take one argument. Continuing
the type variables declared with the original type.
See
on page 4.
the above example, we can define a
type as
That means a synonym like the following is possi-
follows:
ble:
Type
This keyword defines a type synonym (i.e., alias).
This keyword does not define a new type, like
but this not:
or
. It is useful for documenting code but
otherwise has no effect on the actual type of a given
As opposed to
, the
and
“values” on
function or value. For example, a
data type
are not just
values. The typechecker
Note that fewer type variables can be used, which
could be defined as:
treats them as entirely new types. That means our
useful in certain instances.
function from above would not compile.
The following produces a type error:
Where
where the first constructor argument represents
their first name and the second their last. How-
Similar to
,
defines local functions and
ever, the order and meaning of the two arguments
constants. The scope of a
definition is the
is not very clear. A
declaration can help:
current function. If a function is broken into multi-
Instead, we must use pattern-matching to get to the
ple definitions through pattern-matching, then the
“values” to which we apply
:
scope of a particular
clause only applies to
that definition. For example, the function
below has a different meaning depending on the
arguments given to the function
:
Because
introduces a synonym, type checking
The key observation is that this keyword does not
is not affected in any way. The function
, de-
introduce a new value; instead it introduces a new
fined as:
type. This gives us two very useful properties:
No runtime cost is associated with the new
type, since it does not actually produce new
which has the type
values. In other words, newtypes are abso-
lutely free!
Where vs. Let
A
clause can only be de-
The type-checker is able to enforce that com-
fined at the level of a function definition. Usually,
mon types such as
or
are used in
can be used on values with the type
or
that is identical to the scope of
definition. The
restricted ways, specified by the programmer.
just as easily:
only difference is when guards are being used. The
c 2009 Justin Bailey.
8

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education