Haskell Cheat Sheet Page 11

ADVERTISEMENT

Precedence and associativity make many of the
rules of arithmetic work “as expected.” For ex-
ample, consider these minor updates to the prece-
Comprehensions are not limited to numbers. Any
dence of addition and multiplication:
list will do. All upper case letters can be generated:
Of course, full pattern matching, guards, etc. are
available in this form. Type signatures are a bit dif-
ferent, though. The operator “name” must appear
Or, to find all occurrences of a particular break
The results are surprising:
in parentheses:
value
in a list
(indexing from 0):
Allowable symbols which can be used to define op-
erators are:
Reversing associativity also has interesting effects.
A unique feature of list comprehensions is that pat-
Redefining division as right associative:
tern matching failures do not cause an error; they
However, there are several “operators” which can-
are just excluded from the resulting list.
not be redefined. They are:
,
and . The last,
, cannot be redefined by itself, but can be used as
Operators
part of multi-character operator. The “bind” func-
We get interesting results:
tion,
, is one example.
There are very few predefined “operators” in
Haskell—most that appear predefined are actually
Precedence & Associativity
The precedence
syntax (e.g., “ ”). Instead, operators are simply
and associativity, collectively called fixity, of any
functions that take two arguments and have spe-
operator can be set through the
,
and
cial syntactic support. Any so-called operator can
keywords. These can be applied both to
be applied as a prefix function using parentheses:
top-level functions and to local definitions. The
Currying
syntax is:
In Haskell, functions do not have to get all of
|
|
precedence op
To define a new operator, simply define it as a nor-
their arguments at once. For example, consider the
mal function, except the operator appears between
function, which only converts certain
where precedence varies from 0 to 9. Op can actu-
the two arguments. Here’s one which takes inserts
elements of string depending on a test:
ally be any function which takes two arguments
a comma between two strings and ensures no extra
(i.e., any binary operation). Whether the operator
spaces appear:
is left or right associative is specified by
or
, respectively. Such
declarations have
no associativity.
c 2009 Justin Bailey.
11

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education