aleix's blog

The Law of Car

10 April 2013 8:18 AM (scheme | guile)

In The Little Schemer, The Law of Car is defined as:

The primitive car is defined only for non-empty lists.

In the implementation given for (firsts l), it seems to me that the law is broken:

(define firsts
  (lambda (l)
    (cond
      ((null? l) '())
      (else (cons (car (car l))
                  (firsts (cdr l)))))))

As (firsts '()) is '(). So, this would actually fail (in guile):

$ (firsts '((a b) () (e f)))
In procedure firsts:
In procedure car: Wrong type argument in position 1 (expecting pair): ()

I think a correct implementation would be (note that there's no need to write the second cond as the first cond could take multiple clauses):

(define (firsts l)
  (cond
   ((null? l) '())
   (else (cond
          ((null? (car l)) (firsts (cdr l)))
          (else
           (cons (car (car l))
                 (firsts (cdr l))))))))

in which we take care of the non-empty list before getting the first typical element (car (car l)). This would result in:

$ (firsts '((a b) () (e f)))
(a e)

No responses

Leave a Reply