Javaによる関数/ジェネレータの定義

関数

関数は、pnuts.lang.PnutsFunction のサブクラスを定義することで実装できます。

次のクラスは、helloと表示するだけの簡単な関数をJavaで実装します。 この関数にはパラメータがありませんので、defined() メソッドは、引数が0のときだけtrueを返します。 exec()メソッドの最初の部分で引数の数が正しいか検査しています。 それから、"hello"という文字列を標準出力に表示しています。

import pnuts.lang.Context;
import pnuts.lang.PnutsFunction;

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()";
    }
}

ジェネレータ

ジェネレータは、pnuts.lang.Generator のサブクラスを定義することで実装できます。

次のクラスは、ゼロから10個の整数を生成する簡単なジェネレータです。

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)
}

ジェネレータが生成する値をJavaで利用するには、次のようにRuntime.applyGenerator()メソッドを使います。

import pnuts.lang.Runtime;

Runtime.applyGenerator(generator,
                       new PnutsFunction(){
                             protected Object exec(Object[] args, Context ctx){
                                     /*
                                      * args[0] が生成されたオブジェクト
                                      */
                             }
                       },
                       context);