Recursion using Lisp
Added 31 Jul 2008
The last function you're going to create is going to take some recursion, where the true power of list processing using Lisp lies. Iteration is possible (looping through each item one by one), but unlike general languages like the Java language, recursion is by far the easiest way to process lists in Lisp. You'll know exactly what recursion is by the end of this section.
Begin by creating a recursive concat function.
Listing 2. Recursive concatenation (unlimited parameters)
|
Recursion can be a difficult concept to tackle, so lets walk through this one:
- Assume an arbitrary argument list is passed to the above function.
- If there is only one element in the list (the
(cdr args_list)portion on line 2 returns nil), return the single element (the(car args_list)on line 3). - If there is more than one element in the list (meaning the
(cdr args_list)portion on line 2 did not return nil), return the result of concatenating (usingconcat2) the first element of the list (see line 4) and the result of recursively callingconcat_recursiveusing the result of(cdr args_list)as parameters (see line 5).
When passing the following list as a parameter, '("ho" "wd" "y" "
h" "o"), the following is a walk-through of the output:
- The first time line 2 is reached, the
ifstatement is false, andconcat2is called with"ho"and(concat_recursive '("wd" "y" " h" "o")). - The second time line 2 is reached, the
ifstatement is again false, andconcat2is called with"wd"and(concat_recursive '("y" " h" "o")). - The third time line 2 is reached, the
ifstatement is again false, andconcat2is called with"y"and(concat_recursive '(" h" "o")). - The fourth time line 2 is reached, the
ifstatement is again false, andconcat2is called with" h"and(concat_recursive '("o")). - The fifth time is the magical time when the recursion ends. This is because this time,
the
ifstatement on line 2 is now true, and"o"is simply returned. The recursion unwinds as follows:
- Fourth time:
" h"and"o"are concatenated and returned. - Third time:
"y"and" ho"are concatenated and returned. - Second time:
"wd"and"y ho"are concatenated and returned. - First time:
"ho"and"wdy ho"are concatenated and returned as the final result.
- Fourth time:
And there you have it — "howdy ho" ultimately gets returned, as shown below:
COMMON-LISP-USER> |
You have added recursion to your Cusp development arsenal. Try out the debugger next.