This blog will attempt to cover:
- loops in Lisp
- loop for in Lisp
- do loops in Lisp
- how loops and ifs can work together in Lisp
The most basic loop in Lisp is just loop. It loops the action until it sees a condition and return statement.
An example of a basic loop:
Notes on the example:
(terpri) is a command that forces a new line. Otherwise the values would print on one line.
The last line with (when) is the condition that must be met. Then it returns a.
Without the return statement, the loop function will go on infinitely.
This example is taken from the site I am learning from, http://www.tutorialspoint.com/lisp/lisp_loop_construct.htm
The loop function is most closely related to the while in Java.
Next, let's look at the loop for function.
Basic syntax:
(loop for variable from value1 to value2
do ( action )
)
Important to know that the loop goes from value1 to value2 inclusively, as the example below shows:
We'll look at another version of the loop for later in this post.
Next, let's look at the do loop.
Basic syntax:
(do ( ( variable1 startvalue1 updatedvalue1 )
( variable2 startvalue2 updatedvalue2 )
...
( (testcondition) (return value) )
(s expressions)
)
)
s expressions would be used to print the values. We see this in the example below using a function called format, which allows the user to print text and variables. This example was taken from the same site, here's a link: http://www.tutorialspoint.com/lisp/lisp_do.htm
Finally, let's go back to the loop for and play around with an if conditional within the loop.
The syntax is similar to the loop for above, but an if statement is added before the do statement.
The example below shows us multiples of 8 in the range from 1 to 32.
Thanks for reading, I hope this has been interesting. Loops work similar to how a loop would work in Java, and like most things with Lisp, the major difference is in the syntax and how to order the code so that it generates the correct response.
Have a good one,
Peter Short, CS 270, Blog 5