My tail recursive implementation of length is like this:
(define (length2 l)
(define (l-iter l count)
(if (null? 1) count
(l-iter (cdr l) (+ count 1))))
(l-iter l 0))
If I call (length2 '(1 2 3)) and step through the code in racket, count increments to 3 but then on the (if (null? l) count line instead of returning out of the function it goes onto the next line (l-iter (cdr l) (+ count l)))) and of course fails at cder of an empty list.
Racket error message is:
mcdr: contract violation
expected: mpair?
given: '()
I am fairly new to scheme. What am I doing wrong?
Angus