1 package net.sf.saxon.functions; 2 import net.sf.saxon.Err; 3 import net.sf.saxon.expr.XPathContext; 4 import net.sf.saxon.expr.StaticContext; 5 import net.sf.saxon.expr.Optimizer; 6 import net.sf.saxon.expr.ExpressionTool; 7 import net.sf.saxon.om.Item; 8 import net.sf.saxon.om.SequenceIterator; 9 import net.sf.saxon.sort.DescendingComparer; 10 import net.sf.saxon.trans.XPathException; 11 import net.sf.saxon.value.*; 12 13 import java.util.Comparator ; 14 15 18 19 public class Minimax extends CollatingFunction { 20 21 public static final int MIN = 2; 22 public static final int MAX = 3; 23 24 27 28 public void checkArguments(StaticContext env) throws XPathException { 29 super.checkArguments(env); 30 Optimizer opt = env.getConfiguration().getOptimizer(); 31 argument[0] = ExpressionTool.unsorted(opt, argument[0], false); 32 } 33 34 37 38 public Item evaluateItem(XPathContext context) throws XPathException { 39 Comparator collator = getAtomicComparer(1, context); 40 41 if (operation == MAX) { 42 collator = new DescendingComparer(collator); 43 } 44 45 SequenceIterator iter = argument[0].iterate(context); 46 47 AtomicValue min = (AtomicValue)iter.next(); 48 if (min == null) return null; 49 if (min instanceof UntypedAtomicValue) { 50 try { 51 min = new DoubleValue(Value.stringToNumber(min.getStringValueCS())); 52 } catch (NumberFormatException e) { 53 dynamicError("Failure converting " + 54 Err.wrap(min.getStringValueCS()) + 55 " to a number", context); 56 } 57 } 58 59 while (true) { 60 AtomicValue test = (AtomicValue)iter.next(); 61 if (test==null) break; 62 AtomicValue test2 = test; 63 if (test instanceof UntypedAtomicValue) { 64 try { 65 test2 = new DoubleValue(Value.stringToNumber(test.getStringValueCS())); 66 } catch (NumberFormatException e) { 67 dynamicError("Failure converting " + 68 Err.wrap(test.getStringValueCS()) + 69 " to a number", "FORG0001", context); 70 } 71 } 72 if (test2 instanceof NumericValue && ((NumericValue)test2).isNaN()) { 73 return test2; 75 } 76 try { 77 if (collator.compare(test2, min) < 0) { 78 min = test2; 79 } 80 } catch (ClassCastException err) { 81 typeError("Cannot compare " + min.getItemType() + 82 " with " + test2.getItemType(), "FORG0007", context); 83 return null; 84 } 85 } 86 return min; 87 } 88 89 } 90 91 92 | Popular Tags |