neo
neo

Reputation: 69

Error I can't see

(define (length2 item)
  (define (test item count)
  (if (null? item)
      count
     ((+ 1 count) (test item (cdr item)))))
    (test item 0))

Got this as error:

+: contract violation expected: number? given: (2 3) argument position: 2nd other arguments.:

I don't understand what's wrong? I tried to make it iterative.

Upvotes: 0

Views: 43

Answers (1)

Óscar López
Óscar López

Reputation: 235984

There's a problem with the way you're passing the parameters in the recursion, notice that count is the second parameter. This should fix it:

(define (length2 item)
  (define (test item count)
    (if (null? item)
        count
        (test (cdr item) (+ 1 count))))
  (test item 0))

It works as expected:

(length2 '(1 2 3 4 5))
=> 5

Upvotes: 1

Related Questions