10 Apr 2013 aleix   » (Journeyer)

The Law of Car

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:

(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)

Syndicated 2013-04-10 06:18:09 from aleix's blog

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!