In this tutorial we will show how to do operations a specified number of times. In computing, this is referred to as iteration.
Repeating a specified number of times
Suppose we want to write a function to repeatedly print a string a fixed number of times. We could write a recursive definition to solve this:
To repeatedly print a string n times:
- If n is 0 do nothing
- Otherwise print the string, and then repeatedly print the string n-1 times.
Here's this expressed as a Lisp function:
(defun print-times (n) (if (= 0 n) nil (progn (print "Hello") (print-times (- n 1)))))
To get "Hello" printed five times call:
Repeating for a range of numbers
The previous example counts down the value of n from the starting value to zero. We often want to perform an operation for a range of values; for example, we might want to print the squares of the numbers from 15 to 20. Here's the recursive definition:
To print between from and to inclusive:
- If from is larger than to do nothing
- Otherwise print the string, and then print between from+1 and to.
Here it is in Lisp:
(defun print-for (from to) (if (> from to) nil (progn (format t "~a^2 = ~a~%" from (* from from)) (print-for (+ from 1) to))))
Finally, let's test it out:
CL-USER > (print-for 15 20) 15^2 = 225 16^2 = 256 17^2 = 289 18^2 = 324 19^2 = 361 20^2 = 400 NIL
blog comments powered by Disqus