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

521 views
Skip to first unread message

Bo Gus

unread,
Nov 20, 2013, 6:09:28 AM11/20/13
to Racket Newsgroup
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

Pierpaolo Bernardi

unread,
Nov 20, 2013, 6:27:40 AM11/20/13
to Bo Gus, Racket Newsgroup
On Wed, Nov 20, 2013 at 12:09 PM, Bo Gus <forum...@gmail.com> wrote:
> 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))

> I am fairly new to scheme. What am I doing wrong?

You wrote (null? 1), which is always false. Note 1 instead of l.

Cheers
____________________
Racket Users list:
http://lists.racket-lang.org/users

Bo Gus

unread,
Nov 20, 2013, 6:33:18 AM11/20/13
to Racket Newsgroup
I noticed that just after posting.

I changed to:
(define (length2 lst)
  (define (l-iter l count)
    (if (null? l) count
        (l-iter (cdr l) (+ count 1))))
  (l-iter lst 0))

Must get better at spotting obvious mistakes...

Daniel Prager

unread,
Nov 20, 2013, 6:52:17 AM11/20/13
to Bo Gus, Racket Users
Replace the expression (null? 1) with (null? l). You appear to have typed 1 (one) where you meant l (ell).
As a general rule-of-thumb a name such as lst or a-list will reduce the risk of this kind of error.

Dan

Daniel Prager

unread,
Nov 20, 2013, 6:56:25 AM11/20/13
to Bo Gus, Racket Users
Oops - dup.

Didn't see Pierpaolo's reply.

Dan
--
Daniel Prager
Agile/Lean Coaching, Software Development and Leadership
Twitter: @agilejitsu 
Reply all
Reply to author
Forward
0 new messages