Evaluating Lists, or, Function Application in Scheme

Chapter: Evaluating Lists, or, Function Application in Scheme

Now that we have discussed the syntax of lists as data structures in Scheme, let's return to the issue of how lists serve another purpose in the syntax of Scheme. First note that when we have used arithmetic expressions in Scheme, they have had the form of lists; that is to say, they were collections of S-expressions enclosed in parentheses. For example, expressions such as (+ 3 4) and (+ 3 (+ 5 4)).

In mathematics, the expression 3 + 4 is equal to the number 7. Similarly, in Scheme, the expression (+ 3 4) evaluates to 7. But at the same time, we have just discussed the fact that (+ 3 4) is a list!

You may ask, "What's going on here?" You may not. We're going to tell you anyway. Scheme is evaluating the list (+ 3 4), just like it evaluates the constants 3, #t, or any other S-expression that you type at the prompt.

When Scheme evaluates a list, the first thing it does is evaluate all of the elements of that list (this is true as long as the first element of the list is not a keyword (such as cond or quote, introduced later in this lab)). Scheme has a variety of special forms, or keywords, which you will learn about over the course of the quarter. Then, it applies the first element of the list (which must be a function) to the rest of the list. So, in the case of (+ 3 4), Scheme evaluated + to the function representing addition, 3 to the number 3, and 4 to the number 4. Scheme then applied the addition function to its arguments, 3 and 4, and returned the result, the number 7.

This may seem like a very roundabout way of doing things, but consider the following S-expression:

(+ 3 (+ 5 4)) ; This means 3 + ( 5 + 4 )
              ; By the way, the semicolon is the comment character
              ; in scheme. Anything on a line after a semicolon 
              ; is ignored.

The elements of this list are +, 3, and (+ 5 4). Evaluating these S-expressions is not quite as trivial as it was in the previous example. Scheme evaluates + and 3 as before, but when it evaluates the list (+ 5 4), it carries out the addition by evaluating each element of the list, applying the first element to the rest and returning the number 9.

Note that Scheme only prints out the value of the original list. Instead of printing out 9, Scheme applies + to 3 and 9 (the evaluated values of the elements of the original list) and returns 12.


rhyspj@cs.gwu.edu