Question

I have been trying to find the length of a list using scheme using tail recursion and so far, I have this

(define num-els2
  (lambda(xs)
    mynum xs 0))

(define mynum
  (lambda (xs empt)
    (if (empty? xs)
        empt
        (mynum (rest xs) (+ empt 1)))))

but it keeps giving me 0. I think for some reason it does not increment my return value. So how do I fix this?

Was it helpful?

Solution

There is a problem with the parentheses in the num-els2 procedure, nothing serious. Basically, you are not correctly calling the mynum helper procedure, and the procedure is always returning 0, because that's the last expression in the body. Here, this should fix it:

(define num-els2
  (lambda(xs)
    (mynum xs 0))) ; notice the opening bracket in this line

OTHER TIPS

Scheme provides a named let for this:

(define (list-length list)
  (let loop ((list list)
             (length 0))
    (if (null? list)
        length
        (loop (cdr list) (+ length 1)))))

It is part of the standard since R2RS (1985). Earlier it has been called "iterate".

The named let specification is part of the section Iterations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top