Code Comments
Programming Forum and web based access to our favorite programming groups.In PLT scheme I can do this: > (define (f l) (car l)) > (f '(1 2 3)) 1 > (define (f l) (cdr l)) > (f '(1 2 3)) (2 3) > (null? '(1 2 3)) #f > (define (f l) (car l) (if (not (null? l)) (f (cdr l)))) > (f '(1 2 3)) . car: expects argument of type <pair>; given () > It appears to me that in the first 2 lines nothing is wrong with my use of car. However, in the final definition of f, car is used in the same way. When I call the final version of the function f, an error is generated and the problem seems to be my use of car.
Post Follow-up to this messageChairman of The David Hilbert Appreciation Society wrote: > (if (not (null? l)) (f (cdr l)))) > . car: expects argument of type <pair>; given () > > It appears to me that in the first 2 lines nothing > is wrong with my use of car. However, in the final > definition of f, car is used in the same way. When > I call the final version of the function f, an error > is generated and the problem seems to be my use of car. > Run it through trace: (trace f) (f '(1 2 3)) [Entering #[compound-procedure 2 f] Args: (1 2 3)] [Entering #[compound-procedure 2 f] Args: (2 3)] [Entering #[compound-procedure 2 f] Args: (3)] [Entering #[compound-procedure 2 f] Args: ()] ;The object (), passed as the first argument to car, is not the correct type. The empty list is not a pair. -- A. Kanawati NO.antounk.SPAM@comcast.net
Post Follow-up to this message> > (define (f l) (car l) > (if (not (null? l)) (f (cdr l)))) > . car: expects argument of type <pair>; given () > > > It appears to me that in the first 2 lines nothing > is wrong with my use of car. However, in the final > definition of f, car is used in the same way. When > I call the final version of the function f, an error > is generated and the problem seems to be my use of car. Try executing ;(define (f l) (car l) ; (if (not (null? l)) ; (begin ; (display (cdr l)) ; (newline) ; (f (cdr l))))) ; ;(f '(1 2 3)) so that you can see what's happening. The problem is that you are recursively calling f with the current list's cdr, which eventually leads to (f '()). This last invocation of f tries to define (f l) as (car '()), but this is an error because car's argument must be a pair, and the empty list is not a pair. The following code avoids the error by testing whether (cdr l) is null (though it still doesn't really do anything). ;(define (f l) (car l) ; (if (not (null? (cdr l))) ; (f (cdr l)))) HTH, Michael N.B. It's conventional to avoid using "l" as a variable name, since it looks so much like the numeral "1". Use something like "lst" or "seq" instead. (You don't want to use "list", since that would override Scheme's predefined list function.) -- Michael D. Hartl, Ph.D. CTO, Quark Sports LLC http://quarksports.com/
Post Follow-up to this messagePowered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.