Monday, April 15, 2013

Evaluating multiple expressions in Scheme with (begin ...)

I just learned the begin procedure in Scheme. Essentially, this procedure evaluates a number of expressions and returns the last one.

I found it particularly useful in if conditionals where I wanted to evaluate multiple expressions in the true or false clauses. For example, my implementation of for-each in MIT's Structure and Interpretation of Computer Programs Problem 2.23 goes as follows:
(define (for-each proc items)
  (if (null? items)
      #t
      (begin (proc (car items))
             (for-each proc (cdr items)))))
Here, if the list items is not empty, then I apply the procedure in proc to the first element in items and recall for-each, supplying it with the remaining elements in items.

I learned about the begin procedure from this Stack Overflow discussion.