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)
      ((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)
   ((null? l) '())
   (else (cond
          ((null? (car l)) (firsts (cdr l)))
           (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)

One response

  1. assignment writing service says:

    Thank you for your post. I think this post definitely will help students ,especially for programing students.I hope students will easily catch your ideas so that it would become the step by step blog.

Leave a Reply