12.5 Scheme Library

Unlike in Java, the symbol + in Scheme has no special meaning, Instead of translating into a special instruction such as iadd, it is treated just like any other procedure application. The definition of this procedure can be written in Java like this:

 class plus extends Procedure {    /** Add all my arguments together.     * They are expected to be Integers.     */    Object call(Object args[])    {        int sum = 0;        for(int i = 0; i < args.length; i++)             sum += ((Integer) args[i]).intValue();        return new Integer(sum);    } } 

This procedure unwraps each of the arguments and adds them together. At the end they are wrapped up into an Integer object, and that result is returned. It is capable of adding any number of arguments together.

Unlike Java, Scheme permits procedures to be called with any number of arguments of any type. This is why the call method takes an array of Objects as its argument. The form

 (+ 1 2 3 4 5 6 7 8 9 10) 

will result in 55.

In the default Scheme binding environment, the symbol + is bound to an instance of the class plus. The Scheme specification calls for a large library in the default environment. These procedures perform arithmetic, list manipulation, I/O, and other useful functions.

Although plus is written in Java, it meets the requirements of a Scheme procedure: it extends Procedure and overrides call to do something useful. When a Scheme evaluator begins, it creates a default binding environment that is the ancestor of all future binding environments. That way, no matter where the code executes, it is always possible to find the definition of +.

Creation of the global binding environment looks like this:

 // The global environment has no ancestor, so the ancestor is null Environment globalEnv = new Environment(null); globalEnv.bind("+", new plus()); globalEnv.bind("-", new minus()); // A lot of other really handy procedures are implemented in the // default binding environment 

A Scheme evaluator begins with the default binding environment. When a lambda expression is evaluated, its binding environment includes the default binding environment as an ancestor. If that lambda expression causes another lambda expression to be evaluated, as in the example of the add symbol shown earlier, the resulting procedure will also include the default binding environment. In this way, common symbols like + are made available to all procedures. We have taken a shortcut here: plus and minus, unlike lambda expressions, do not use the environment, so we don't initialize the env field.



Programming for the Java Virtual Machine
Programming for the Javaв„ў Virtual Machine
ISBN: 0201309726
EAN: 2147483647
Year: 1998
Pages: 158
Authors: Joshua Engel

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net