Functions can be written in Java, following these steps.
The following class implements a simple function just prints "hello". Since this function has no parameter, defined() method returns true only when the argument is 0. The first part of exec() method checks if the number of parameters is correct. Then it prints "hello" to the standard output.
import pnuts.lang.Context;
import pnuts.lang.Package;
public class hello extends PnutsFunction {
public hello(){
super("hello");
}
public boolean defined(int nargs){
return (nargs == 0);
}
protected Object exec(Object[] args, Context context){
int nargs = args.length;
if (nargs != 0){
undefined(args, context);
return null;
}
System.out.println("hello");
return null;
}
public String toString(){
return "function hello()";
}
}
Generators can be written in Java, following these steps.
The following class implements a simple generator that generates 10 integers from zero.
import pnuts.lang.*;
public class MyGenerator extends Generator {
public Object apply(PnutsFunction closure, Context context){
for (int i = 0; i < 10; i++){
closure.call(new Object[]{new Integer(i)}, context);
}
return null;
}
}
for (i : MyGenerator()){
println(i)
}
To use generated objects in Java, use Runtime.applyGenerator() method as follows.
import pnuts.lang.Runtime;
Runtime.applyGenerator(generator,
new PnutsFunction(){
protected Object exec(Object[] args, Context ctx){
/*
* args[0] is the generated object
*/
}
},
context);