01: // Copyright (c) 2002 Per M.A. Bothner.
02: // This is free software; for terms and warranty disclaimer see ./COPYING.
03:
04: package gnu.xquery.util;
05:
06: import gnu.mapping.*;
07: import gnu.lists.*;
08: import gnu.math.*;
09: import gnu.kawa.functions.AddOp;
10:
11: public class Average extends Procedure1 {
12: public static final Average avg = new Average("avg");
13:
14: public Average(String name) {
15: super (name);
16: }
17:
18: public Object apply1(Object arg) throws Throwable {
19: Object sum = Values.empty;
20: int count = 0;
21: if (arg instanceof Values) {
22: TreeList tlist = (TreeList) arg;
23: int index = 0;
24: for (;;) {
25: Object next = tlist.getPosNext(index);
26: if (next == Sequence.eofValue)
27: break;
28: count++;
29: sum = sum == Values.empty ? next : ArithOp.add.apply2(
30: sum, next);
31: index = tlist.nextPos(index);
32: }
33: } else {
34: count = 1;
35: sum = arg;
36: }
37: if (sum == Values.empty)
38: return sum;
39: return sum = ArithOp.div.apply2(sum, IntNum.make(count));
40: }
41: }
|