In Scheme, falsity is represented by the value false, written
#f
. Conceptually, #f
is a pointer to a special object,
the false object.
Predicates are procedures that return either #t
or #f
,
and don't have side effects. Calling a predicate is like asking a
true/false question--all you care about is a yes or no answer.
Try out the "greater-than" predicate >
.
Scheme>(> 1 2) #f
Here we told Scheme to apply the predicate procedure to 1 and 2; it
returned #f
and Scheme printed that.
The important thing about #f
is its use in conditionals. If the
first subexpression (the condition) of an if
expression
returns the value #f
, the second subexpression is not evaluated, and
the third one is; that value is returned as the value of the if
expression.
Try just using the literal value #f
as the first subexpression
of an if
, i.e., the "condition" that controls which branch
is taken.
Scheme>(if #f 1 2) 2
Here the second subexpression was just the literal 2
, so 2
was returned.
Now try it using the predicate >
Scheme>(if (> 1 2) 1 2) 2
This is clearer if we indent it like this, lining up the "then" part (the consequent) and the "else" part (the alternative) under the condition.
Scheme>(if (> 1 2) 1 2) 2
This is the right way to indent code when writing a Scheme program in an
editor, and most Scheme systems will let you indent code this way when
using the system interactively--the you can hit <RETURN>
, and type
in extra spaces. Scheme won't try to evaluate the expression until you
write the last closing parenthesis and hit <RETURN>
. This helps
you format your code readably even when typing interactively, so that
you can see what you're doing.
The false value makes a conditional expression (like an if
) go
one way, and a true value will make it go another. In Scheme, any
value except #f
counts as true in conditionals. Try this:
Scheme> (if 0 1 0)
What result value does Scheme print?
One special value is provided, called the true object, written
#t
. There's nothing very special about it, though--it's just
a handy value to use when you want to return a true value, making
it clear that all you're doing is returning a true value.
Scheme>(if #t 1 2) 1
Scheme>(if (> 2 1) 1 2) 1
Now let's interactively define the procedure min
, and then call
it:
Scheme> (define (min a b) (if (< a b) a b)) #void Scheme> (min 30 40) 30