50 lines
2 KiB
HTML
50 lines
2 KiB
HTML
|
<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">
|
||
|
<!Originally converted to HTML using LaTeX2HTML 95 (Thu Jan 19 1995) by Nikos Drakos (nikos@cbl.leeds.ac.uk), CBLU, University of Leeds >
|
||
|
<HEAD>
|
||
|
<TITLE> If</TITLE>
|
||
|
</HEAD>
|
||
|
<BODY>
|
||
|
<meta name="description" value=" If">
|
||
|
<meta name="keywords" value="lp">
|
||
|
<meta name="resource-type" value="document">
|
||
|
<meta name="distribution" value="global">
|
||
|
<P>
|
||
|
<BR> <HR>
|
||
|
<A HREF="node23.html"><IMG ALIGN=BOTTOM ALT="next" SRC="next_motif.gif"></A>
|
||
|
<A HREF="node21.html"><IMG ALIGN=BOTTOM ALT="up" SRC="up_motif.gif"></A>
|
||
|
<A HREF="node21.html"><IMG ALIGN=BOTTOM ALT="previous" SRC="previous_motif.gif"></A> <BR>
|
||
|
<A HREF="lp.html"><B>Contents</B></A>
|
||
|
<B> Next:</B>
|
||
|
<A HREF="node23.html"> Cond</A>
|
||
|
<B>Up:</B>
|
||
|
<A HREF="node21.html"> Conditional Control</A>
|
||
|
<B> Previous:</B>
|
||
|
<A HREF="node21.html"> Conditional Control</A>
|
||
|
<BR> <HR> <P>
|
||
|
<H2> If</H2>
|
||
|
<P>
|
||
|
An if statement has the form:
|
||
|
<BLOCKQUOTE>
|
||
|
<PRE> (if <test> <then> <else> )
|
||
|
</PRE>
|
||
|
</BLOCKQUOTE>
|
||
|
The test, then, and else expressions can be any evaluable Lisp expressions -- e.g., symbols or lists. If the evaluation of the test expression returns anything other than nil, e.g. T, 3, FOO, (A S D F), the interpreter evaluates the then expression and returns its value, otherwise it returns the result of evaluating the else expression.
|
||
|
<P>
|
||
|
We can use if to define a function to return the absolute difference between two numbers, by making use of the predicate <b>> </b> (greater than). Here it is:
|
||
|
<BLOCKQUOTE>
|
||
|
<PRE>(defun absdiff (x y)
|
||
|
(if (> x y)
|
||
|
(- x y)
|
||
|
(- y x)))
|
||
|
</PRE>
|
||
|
</BLOCKQUOTE>
|
||
|
If x is greater than y, then the test, i.e. (<b>> </b> x y), returns T, so the then clause is evaluated, in this case (- x y), which gives the positive difference. If x is less than or equal to y, then the expression (- y x) gets evaluated, which will return 0 or a positive difference.
|
||
|
<P>
|
||
|
<BR> <HR>
|
||
|
<P>
|
||
|
<ADDRESS>
|
||
|
<I>© Colin Allen & Maneesh Dhagat <BR>
|
||
|
March 2007 </I>
|
||
|
</ADDRESS>
|
||
|
</BODY>
|