Evaluating Scheme expressions from Java

The following methods are recommended if you need to evaluate a Scheme expression from a Java method. (Some details (such as the ‘throws’ lists) may change.)

Static method: void Scheme.registerEnvironment ()

Initializes the Scheme environment. Maybe needed if you try to load a module compiled from a Scheme source file.

Static method: Object Scheme.eval (InPort port, Environment env)

Read expressions from port, and evaluate them in the env environment, until end-of-file is reached. Return the value of the last expression, or Interpreter.voidObject if there is no expression.

Static method: Object Scheme.eval (String string, Environment env)

Read expressions from string, and evaluate them in the env environment, until the end of the string is reached. Return the value of the last expression, or Interpreter.voidObject if there is no expression.

Static method: Object Scheme.eval (Object sexpr, Environment env)

The sexpr is an S-expression (as may be returned by read). Evaluate it in the env environment, and return the result.

For the Environment in most cases you could use ‘Environment.current()’. Before you start, you need to initialize the global environment, which you can with

Environment.setCurrent(new Scheme().getEnvironment());

Alternatively, rather than setting the global environment, you can use this style:

Scheme scm = new Scheme();
Object x = scm.eval("(+ 3 2)");
System.out.println(x);