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?

有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top