emacs.d/clones/colinallen.dnsalias.org/lp/node22.html

49 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 &lt;test&gt; &lt;then&gt; &lt;else&gt; )
</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>&gt; </b> (greater than). Here it is:
<BLOCKQUOTE>
<PRE>(defun absdiff (x y)
(if (&gt; x y)
(- x y)
(- y x)))
</PRE>
</BLOCKQUOTE>
If x is greater than y, then the test, i.e. (<b>&gt; </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>&#169; Colin Allen &amp; Maneesh Dhagat <BR>
March 2007 </I>
</ADDRESS>
</BODY>