Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
The get-prop function for property lists


Here is a possible solution:

(define (get-prop key property-list)
  (cond ((null? property-list) #f)
        ((null? (cdr property-list))
           (error "Malformed property list"))
        ((equal? key (car property-list))
           (cadr property-list))
        (else (get-prop key (cdr (cdr property-list))))))

I see a number of problems and issues with property lists and get-prop:

The last observation could give rise to an alternative solution, which returns a list of (key value) in case key is found, and #f if the key is not found:

(define (get-prop key property-list)
  (cond ((null? property-list) #f)
        ((null? (cdr property-list))
           (error "Malformed property list"))
        ((equal? key (car property-list))
           (list key (car (cdr property-list))))
        (else (get-prop key (cdr (cdr property-list))))))

However, this requires allocation of two new cons cells (in contrast to association lists, where no new cons cell allocation is necessary). Please understand this.