문제

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