1

One of the first questions in the second chapter of The Little Schemer (4th edition) asks the reader to write the function lat?, where (lat? l) returns true if l is a list of atoms.

It goes on to say:

You were not expected to be able to do this yet, because you are still missing some ingredients.

But I'm familiar with recursion, and the definition of atom? earlier in the book already introduced and (further implying the existence of or), so I gave it a shot anyway: (repl)

(define lat?
  (lambda (l)
    (or
      (null? l)
      (and
        (atom? (car l))
        (lat? (cdr l))))))

On the next page, the book introduces the cond operator to enable this definition of lat?:

(define lat?
  (lambda (l)
    (cond
      ((null? l) #t)
      ((atom? (car l)) (lat? (cdr l)))
      (else #f))))

Is there any significant difference between these two implementations?

  • 3
    no. except for the actual, not implied, existence of `or`; which that `cond` expression is defining, effectively. – Will Ness Nov 12 '17 at 19:35

1 Answers1

1

cond is a special form, that takes (roughly) the form

(cond
  ((test-expression) (then-expression))
  ((test-expression2) (then-expression2))
  (else
   (then-expression3)))

Its semantics is that it will evaluate the test-expressions in order, and for the first one that it finds to evaluate to #t (the true value), then it will evaluate its associated then-expression and return its value. If all the test-expressions evaluate to #f (the false value), and an else clause is present, then it will evaluate its associated then-expression3 in this case, and return its value.

So as far as semantics are concerned, the two implementations are equivalent. Their only difference might be that afaik the cond version is considered more idiomatic in the Scheme community.

NlightNFotis
  • 9,559
  • 5
  • 43
  • 66