KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gnu > kawa > functions > Apply


1 package gnu.kawa.functions;
2 import gnu.lists.*;
3 import gnu.mapping.*;
4
5 /** Implement the standard Scheme function "apply".
6  * This has been generalized so that the last (list argument)
7  * can be any sequence, or any primitive array coercible to Object[]. */

8
9 public class Apply extends ProcedureN
10 {
11   public static final Apply apply = new Apply();
12   static { apply.setName("apply"); }
13
14   private Object JavaDoc[] getArguments (Object JavaDoc[] args, int skip)
15   {
16     int count = args.length;
17     if (count < skip + 1)
18       throw new WrongArguments("apply",2,"(apply proc [args] args) [count:"+count+" skip:"+skip+"]");
19     Object JavaDoc last = args[count-1];
20     int last_count;
21     if (last instanceof Object JavaDoc[])
22       {
23     Object JavaDoc[] last_arr = (Object JavaDoc[]) last;
24     if (count == 2)
25       return last_arr;
26     last_count = last_arr.length;
27       }
28     else if (last instanceof Sequence)
29       last_count = ((Sequence)last).size();
30     else
31       last_count = -1;
32     if (last_count < 0)
33       throw new WrongType(this, count, last, "sequence or array");
34     int numArgs = last_count + (count - skip - 1);
35     Object JavaDoc[] proc_args = new Object JavaDoc[numArgs];
36     int i;
37     for (i = 0; i < count - skip - 1; i++)
38       proc_args[i] = args[i+skip];
39     if (last instanceof Object JavaDoc[])
40       {
41     System.arraycopy((Object JavaDoc[]) last, 0,
42              proc_args, i, last_count);
43       }
44     else
45       {
46     while (last instanceof Pair)
47       {
48         Pair pair = (Pair) last;
49         proc_args[i++] = pair.car;
50         last = pair.cdr;
51         last_count--;
52       }
53     if (last_count > 0)
54       {
55         Sequence last_seq = (Sequence) last;
56         for (int j = 0; j < last_count; j++)
57           proc_args[i++] = last_seq.get(j);
58       }
59       }
60     return proc_args;
61   }
62
63   public static Object JavaDoc doApply(Procedure proc, Object JavaDoc[] args) throws Throwable JavaDoc
64   {
65     return proc.applyN(apply.getArguments(args, 0));
66   }
67
68   public Object JavaDoc applyN (Object JavaDoc[] args) throws Throwable JavaDoc
69   {
70     return ((Procedure) args[0]).applyN(getArguments(args, 1));
71   }
72
73   public void apply (CallContext ctx) throws Throwable JavaDoc
74   {
75     Object JavaDoc[] args = ctx.getArgs();
76     ((Procedure) args[0]).checkN(getArguments(args, 1), ctx);
77   }
78 }
79
Popular Tags