Haskell Cheat Sheet Page 5

ADVERTISEMENT

If and IO
can be tricky when used with
IO. Conceptually it is no different from an
in
any other context, but intuitively it is hard to de-
velop. Consider the function
from
:
An alternative syntax uses semi-colons and braces.
Again, notice where
is. We don’t put it in
A
is still required, but indention is unnecessary.
the
statement. Instead we use it once at the end
The
statement has this “signature”:
This code shows a
example, but the principle
of the function.
applies to
as well:
Multiple
’s
When using
with
or
,
That is, it takes a
value and evaluates to some
another
is required if either branch has multiple
other value based on the condition. From the type
statements. An example with
:
signatures it is clear that
cannot be
used directly by
:
That is,
results in an
value,
while
wants a
value. Instead, the correct
Export
value must be “extracted” by running the IO ac-
tion:
See the section on
on page 6.
If, Then, Else
Remember,
always “returns” a value. It is an
expression, not just a control flow statement. This
function tests if the string given starts with a lower
And one with
:
Notice the use of
. Because
puts us “in-
case letter and, if so, converts it to upper case:
side” the
monad, we can’t “get out” except
through
. Note that we don’t have to use
inline here—we can also use
to evaluate the
condition and get a value first:
c 2009 Justin Bailey.
5

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education