This blog will discuss:
- Conditionals in LISP
We're going to start off with a simple if statement.
The basic syntax structure looks like this:
(if ( [test-clause] ) ( [action if true] ) ( [action if false] ) )
We'll test to see if an integer is positive, if it is it'll return positive, if not, it will return NIL, this is LISP's version of false.
In LISP we can use a single quote ( ' ) as like a return statement for printing the result of our conditional... An example of this syntax is found in the next example where we look at some integers and determine if they're even or odd.
The code works by testing if any given value mod 2 is equal to 0, if this tests to be true, it must be even, so we return even, otherwise it must be false, so we return odd.
Next, we'd like to test one value with three conditions, whether it's positive, negative, or zero. To do this, we'll create three variables, using defvar.
For the comparison we'll use a cond function, the syntax for which is described as:
( cond ( (test1) (action1) ) ( (test2) (action2) ) ... ( (testN) (actionN) ) )
So, we'll try using this feature of LISP to test our values.
Next, we'll combine the two tests, and change testval1 to 10. We'll have the program to print whether the value is positive/ negative / or zero, and if the value is even or odd.
First changing the variable, easily done using the setq function:
Next, we'll use cond to complete the conditionals again:
Biggest challenge I found with this program was keeping track of the parentheses, so be careful with those. I think that will be the biggest cause of errors going forward.
I hope this was enjoyable, leave a comment down below if you have any questions.
Peter Short, CS 270, February 17, 2016, Blog #4