On Scheme

Thoughts on Scheme and teaching Scheme

Explaining Let in Terms of Lambda

Posted by Peter on March 11, 2006

Most explanations of let simply explain it as creating temporary symbols which can be assigned values, and that these symbols can only be reached within the body of the let. This is a perfectly valid and informative way of describing how let functions, but I decided to explain it in a different fashion, by appealing to programming constructs already understood by the student. (I assume that the student has already mastered the basics of the lambda statement, realizing that it can be returned from functions, passed to functions, as well as called immediately.)

To motivate the learning process I ask the student how they would go about printing user input, acquired from (read) twice. At first the student may think this is impossible, as if they call read again they will be prompting the user for input again, which is not what they want. So then I ask them if they can write a function taking one argument that prints its argument twice. This is easy enough to do, and once they have this function than printing the user input twice is no problem. Now, to make life more difficult I ask if they can accomplish the same thing in a single function. The brightest students may make the conceptual leap and see that they can do this with lambda, but after demonstrating it even those don’t make the conceptual leap seem to get it. So the program we are writing may look like this:

(defun printtwice ()
  ((lambda (val)
      (display val)
      (display val))

To make things sink in we then cover more examples using this same technique, which also has the benefit of reinforcing how lambda can be used. After the students seem to get it I then introduce let as a kind of shorthand for this construction. (now that I think of it writing let as a macro in terms of this construction may be a good exercise for macros.) I then rewrite our examples using let, so our first example becomes:

(defun printtwice()
  (let ((val (read)))
      (display val)
      (display val)))

The only real difficulty I have had is explaining why there are two parenthesis around ((val (read))) instead of one. Examples involving more than one name defined by the let statement show the students why it is necessary in order for the computer to understand their code, but even so they have a tendency to forget them.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: