Haskell Cheat Sheet Page 9

ADVERTISEMENT

scope of the
clause extends over all guards.
bind the value to. This facility is used below to
In contrast, the scope of a
expression is only
bind the head of the list in
for display, while also
and recalling the
definition of
from page
2
the current function clause and guard, if any.
binding the entire list to
in order to compute its
we can match on nested
values when
is
length:
present:
Declarations, Etc.
The following section details rules on function dec-
larations, list comprehensions, and other areas of
the language.
Pattern-matching also allows values to be assigned
Guards
Boolean functions can be used as
to variables. For example, this function determines
Function Definition
“guards” in function definitions along with pattern
if the string given is empty or not. If not, the value
matching. An example without pattern matching:
bound to
is converted to lower case:
Functions are defined by declaring their name, any
arguments, and an equals sign:
All functions names must start with a lowercase let-
Note that
above is similer to
in that it will
ter or “ ”. It is a syntax error otherwise.
match anything; the only difference is that the
Notice
– it always evaluates to true and
value matched is also given a name.
can be used to specify a “default” branch.
Pattern Matching
Multiple “clauses” of a func-
Guards can be used with patterns. Here is a
tion can be defined by “pattern-matching” on the
n
k Patterns
This (sometimes controversial)
function that determines if the first character in a
values of arguments. Here, the the
function
pattern-matching facility makes it easy to match
string is upper or lower case:
has four separate cases:
certain kinds of numeric expressions.
The idea
is to define a base case (the “n” portion) with a
constant number for matching, and then to define
other matches (the “k” portion) as additives to the
base case. Here is a rather inefficient way of testing
if a number is even or not:
Matching & Guard Order
Pattern-matching
proceeds in top to bottom order. Similarly, guard
expressions are tested from top to bottom. For ex-
ample, neither of these functions would be very in-
Note that the ‘ ’ character is a wildcard and
Argument Capture
Argument capture is useful
teresting:
matches any value.
for pattern-matching a value and using it, without
Pattern matching can extend to nested values.
declaring an extra variable. Use an ‘ ’ symbol in
Assuming this data declaration:
between the pattern to match and the variable to
c 2009 Justin Bailey.
9

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education