I am trying to write two separate tail recursive functions that compute the length of a list and I am given these limitations:
-
write a version,
lengthtthat is tail recursive and uses external (non-nested) auxiliary functions as needed -
write a second version,
lengtht2that uses no additional top-level functions. The function should still be tail-recursive, and can use any local bindings that you want
I am new to racket and this is what I understand the general form of tail recursion is:
(define (func x)
(cond (end-test-1 end-value-1)
(end-test-2 end-value-2)
(else (func reduced-x))))
I am just a little confused about how to do this
This looks like homework, so I’ll give you some hints to point you in the right direction, and you can fill-in the blanks. Try this for the first question:
Try this for the second question:
In any case, think for a moment: what’s the length of an empty (null) list? the answer will show you how to initialize the iteration. And for both solutions, we use an extra parameter called
accfor keeping track of the answer so far, and we pass it along with the list to a looping tail-recursive procedure.