Bombproof Code

The function cadr must be given a list of at least two elements; otherwise it will signal an error.


(cadr (assoc 'dos '((one 1) (two 2))))
will generate an error.


(define (safe-cadr lst)
  (if (pair? lst)
      (if (pair? (cdr lst))
          (cadr lst)
          #f)
      #f) )

(safe-cadr (assoc 'dos '((one 1) (two 2)))) = #f

Rule: Check data types before performing an access that could cause an error.

Contents    Page-10    Prev    Next    Page+10    Index