01: /*
02: * @(#)range.java 1.2 04/12/06
03: *
04: * Copyright (c) 2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import pnuts.lang.PnutsFunction;
12: import pnuts.lang.Context;
13: import pnuts.lang.Generator;
14:
15: public class range extends PnutsFunction {
16: public range() {
17: super ("range");
18: }
19:
20: public boolean defined(int nargs) {
21: return nargs == 2;
22: }
23:
24: protected Object exec(Object[] args, final Context context) {
25: if (args.length != 2) {
26: undefined(args, context);
27: return null;
28: }
29: int i0, i1;
30: Object arg0 = args[0];
31: if (arg0 instanceof Number) {
32: i0 = ((Number) arg0).intValue();
33: } else {
34: throw new IllegalArgumentException(String.valueOf(arg0));
35: }
36: Object arg1 = args[1];
37: if (arg1 instanceof Number) {
38: i1 = ((Number) arg1).intValue();
39: } else {
40: throw new IllegalArgumentException(String.valueOf(arg1));
41: }
42: class G extends Generator {
43: int start;
44: int end;
45:
46: G(int start, int end) {
47: this .start = start;
48: this .end = end;
49: }
50:
51: public Object apply(PnutsFunction closure, Context ctx) {
52: int s = this .start;
53: int e = this .end;
54: Object[] args = new Object[1];
55: if (s > e) {
56: for (int i = s; i >= e; i--) {
57: args[0] = new Integer(i);
58: closure.call(args, context);
59: }
60: } else {
61: for (int i = s; i <= e; i++) {
62: args[0] = new Integer(i);
63: closure.call(args, context);
64: }
65: }
66: return null;
67: }
68: }
69: return new G(i0, i1);
70: }
71:
72: public String toString() {
73: return "function range(start, end)";
74: }
75: }
|