Haskell Cheat Sheet Page 10

ADVERTISEMENT

the type of a particular value, even if the value isn’t
code when using a
constructor.
present.
has type
but, if not enough other informa-
For example, define a class for default values:
tion is available, Haskell must be told what
is.
Some example default values:
Record Syntax
Normally pattern matching oc-
The idea is you give
a value of the right
curs based on the position of arguments in the
type and it gives you back a default value for that
value being matched. Types declared with record
type. Defining instances for basic types is easy:
syntax, however, can match based on those record
names. Given this data type:
List Comprehensions
A list comprehension consists of four types of ele-
ments: generators, guards, local bindings, and targets.
A list comprehension creates a list of target values
based on the generators and guards given. This
we can match on
only:
is a littler trickier, because we want to get
comprehension generates all squares:
a default value for the type, but the constructor
might be
. The following definition would
work, but it’s not optimal since we get
generates a list of all
values
when
is passed in.
Argument capture is possible with this syntax, al-
and puts them in , one by one.
creates each
though it gets clunky. Continuing the above, we
element of the list by multiplying
by itself.
now define a
type and a function to replace
Guards allow certain elements to be excluded.
values with non-zero
components with all
The following shows how divisors for a given num-
black:
ber (excluding itself) can be calculated. Notice how
We’d rather get a
default value back instead.
is used in both the guard and target expression.
Here is where a lazy pattern saves us – we can pre-
tend that we’ve matched
and use that to get
a default value, even if
is given:
Local bindings provide new definitions for use in
the generated expression or subsequent generators
Lazy Patterns
This syntax, also known as ir-
As long as the value
is not actually evaluated,
and guards. Below,
is used to represent the mini-
refutable patterns, allows pattern matches which al-
we’re safe. None of the base types need to look at
mum of
and :
ways succeed. That means any clause using the
(see the “ ” matches they use), so things will work
pattern will succeed, but if it tries to actually use
just fine.
the matched value an error may occur. This is gen-
One wrinkle with the above is that we must
erally useful when an action should be taken on
provide type annotations in the interpreter or the
c 2009 Justin Bailey.
10

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education