Contents
Page-10
Prev
Next
Page+10
Index
Tail Recursive Processing of List
A function is tail recursive if it either
- returns an answer directly, e.g return 0;
- the answer is exactly the result of a recursive call,
return myself( something);
Tail recursion often involves the use of an extra function
with extra variables as parameters:
think of picking apples and putting them into a bucket as you go;
the bucket is an extra variable.
The main function just initializes the extra variables, while the
helper function does the work.[Note that we define the
helper function first: otherwise, the Clojure compiler will generate
an error when the main function calls it before it is defined.]
(defn lengthb [lst answer]
(if (empty? lst) ; test for base case
answer ; answer for base case
(lengthb (rest lst) ; recursive call
(+ answer 1)) ) ) ; update answer
(defn length [lst]
(lengthb lst 0)) ; init answer variable