Scheme Programming/Procedures

So far, we've worked with many built-in Scheme procedures (like +, *, etc.), but we haven't seen how to define our own. Procedures are created with the lambda form. Here's a simple example:

Evaluating a  form gives us back a procedure object, which we can treat like any other value. Unlike the built-in procedures that we've been working with, though, this procedure lacks something important--a name. The procedures constructed with lambda are thus called "anonymous"; if we want to apply them, we have to write out the lambda expression as the operator of an application:

How does this work? As we saw in previous sections, we evaluate an application of a procedure to some arguments by first evaluating both the operator (which is  here) and the operands. Our lambda expression evaluates to an (anonymous) procedure of one argument, x, which returns the value of x squared. Applied to the value 4, this procedure returns 16.

Naming procedures
It's impractical--though certainly not impossible--to write programs using only anonymous procedures. Even relatively simple programs would become unbearably complicated if we had to write lambda expressions for every operator, rather than using convenient names. Since procedures are values, we can gives names to them with define, just as we can any other value:

Here, we define  to mean the procedure . Once this is done, we can use square as a procedure anywhere we like. Scheme makes no distinction between built-in and newly-defined procedures, so procedure definitions are a crucial way in which Scheme programmers extend the language.

It's a bit clumsy to have to write every time we want to write a procedure, so Scheme provides a shorthand. We can also write our definition of square as follows:

The general form of this shorthand is:

This definition is the same as the one with the explicit <tt>lambda</tt> expression, but it's a little quicker to type. You'll see this form of definition constantly in Scheme code.

Variable number of arguments
You can also create procedures with a variable number of arguments:

This will create procedure sum which works identically to the native + procedure.

This is the same as:

Note that there are no parentheses around the args parameter so all arguments will be put into one list named args.

With lambda, if you want to have one fixed argument and the rest of the arguments optional you can use an improper list:

With this, you can create procedures with optional arguments:

This will create a procedure that evaluates  when no second argument is provided or.