1 package com.icl.saxon.functions; 2 import com.icl.saxon.*; 3 import com.icl.saxon.om.NodeInfo; 4 import com.icl.saxon.om.NodeEnumeration; 5 import com.icl.saxon.expr.*; 6 7 import java.util.*; 8 9 10 public class Sum extends Function { 11 12 15 16 public String getName() { 17 return "sum"; 18 }; 19 20 24 25 public int getDataType() { 26 return Value.NUMBER; 27 } 28 29 32 33 public Expression simplify() throws XPathException { 34 checkArgumentCount(1, 1); 35 argument[0] = argument[0].simplify(); 36 37 if (argument[0] instanceof Value) { return evaluate(null); 39 } 40 return this; 41 } 42 43 46 47 public double evaluateAsNumber(Context c) throws XPathException { 48 NodeEnumeration nsv = argument[0].enumerate(c, false); 49 return total(nsv); 50 } 51 52 55 56 public Value evaluate(Context c) throws XPathException { 57 return new NumericValue(evaluateAsNumber(c)); 58 } 59 60 63 64 public int getDependencies() { 65 return argument[0].getDependencies(); 66 } 67 68 71 72 public Expression reduce(int dep, Context c) throws XPathException { 73 Sum f = new Sum(); 74 f.addArgument(argument[0].reduce(dep, c)); 75 f.setStaticContext(getStaticContext()); 76 return f.simplify(); 77 } 78 79 82 83 private static double total(NodeEnumeration enum) throws XPathException { 84 85 double sum = 0.0; 86 while (enum.hasMoreElements()) { 87 String val = enum.nextElement().getStringValue(); 88 sum += Value.stringToNumber(val); 89 } 90 return sum; 91 } 92 93 } 94 95 96 | Popular Tags |