[racket] Why does this tail recursive list length function fail at cdr l at end of list?

From: Bo Gus (forumangus at gmail.com)
Date: Wed Nov 20 06:09:28 EST 2013

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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20131120/f8e32426/attachment.html>

Posted on the users mailing list.