XML technologies / XSLT / XSLT Cookbook / Numbers and calculations / Finding maxima and minima

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

Find the smallest or largest numeric node or nodes in a node set.

Solution

XSLT 1.0

The EXSLT functions for these operations are exsl:min, exsl:max, exsl:lowest and exsl:highest. Functions min and max return the minimum and maximum numeric values. EXSLT defines exsl:min as follows:

  • The minimum is defined by sorting the supplied node set in ascending order, as with xsl:sort using data type number. Convert the first sorted node’s string value to a number using number to obtain the minimum.

  • If the set is empty or any node’s conversion produces NaN, return NaN.

exsl:max is defined similarly. EXSLT supplies pure XSLT implementations following these definitions literally:

Example: EXSLT min and max implemented directly from their definitions.

<xsl:template name="ckbk:min">
  <xsl:param name="nodes" select="/.." />
  <xsl:choose>
    <xsl:when test="not($nodes)">NaN</xsl:when>
    <xsl:otherwise>
      <xsl:for-each select="$nodes">
        <xsl:sort data-type="number" />
        <xsl:if test="position() = 1">
          <xsl:value-of select="number(.)" />
        </xsl:if>
      </xsl:for-each>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>
<xsl:template name="ckbk:max">
  <xsl:param name="nodes" select="/.." />
  <xsl:choose>
    <xsl:when test="not($nodes)">NaN</xsl:when>
    <xsl:otherwise>
      <xsl:for-each select="$nodes">
        <xsl:sort data-type="number" order="descending" />
        <xsl:if test="position() = 1">
          <xsl:value-of select="number(.)" />
        </xsl:if>
      </xsl:for-each>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

The default for parameter nodes may seem puzzling (select="/ .. "). It is an idiom initializing nodes to an empty set: the root’s parent is empty by definition.

The definitions of ckbk:min and ckbk:max use xsl:sort, but implementations need not. More efficient versions are possible if your XSLT processor supports tail recursion, as below.

Example: Divide-and-conquer min and max.

<xsl:template name="ckbk:max">
  <xsl:param name="nodes" select="/.."/>
  <xsl:param name="max"/>
  <xsl:variable name="count" select="count($nodes)"/>
  <xsl:variable name="aNode" select="$nodes[ceiling($count div 2)]"/>
  <xsl:choose>
    <xsl:when test="not($count)">
      <xsl:value-of select="number($max)"/>
    </xsl:when>
    <xsl:when test="number($aNode) != number($aNode)">
      <xsl:value-of select="number($aNode)"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:call-template name="ckbk:max">
        <xsl:with-param name="nodes" select="$nodes[not(. <= number($aNode))]"/>
        <xsl:with-param name="max">
          <xsl:choose>
            <xsl:when test="not($max) or $aNode &gt; $max">
              <xsl:value-of select="$aNode"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="$max"/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:with-param>
      </xsl:call-template>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>
<xsl:template name="ckbk:min">
  <xsl:param name="nodes" select="/.."/>
  <xsl:param name="min"/>
  <xsl:variable name="count" select="count($nodes)"/>
  <xsl:variable name="aNode" select="$nodes[ceiling($count div 2)]"/>
  <xsl:choose>
    <xsl:when test="not($count)">
      <xsl:value-of select="number($min)"/>
    </xsl:when>
    <xsl:when test="number($aNode) != number($aNode)">
      <xsl:value-of select="number($aNode)"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:call-template name="ckbk:min">
        <xsl:with-param name="nodes" select="$nodes[not(. &gt;= number($aNode))]"/>
        <xsl:with-param name="min">
          <xsl:choose>
            <xsl:when test="not($min) or $aNode &lt; $min">
              <xsl:value-of select="$aNode"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="$min"/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:with-param>
      </xsl:call-template>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

These implementations are usually faster than versions using xsl:sort, but occasionally slower. Efficiency depends on eliminating roughly half the nodes per recursive step. Imagine a case where aNode is the remaining minimum for ckbk:max or maximum for ckbk:min. Only one node would then be removed per step, giving poor performance. Fortunately, data is usually presorted or random; both should work well.

Non-numeric data still needs explicit detection. EXSLT leaves that to xsl:sort. XSLT requires non-numeric values to sort first when data-type='number' is specified.

Warning!
Do not write not(number($var)) to test for NaN! It sounds right, but function number does not test for a number; it converts its argument to a number. Conversion of 0 to false makes this test treat zero as non-numeric. The correct test is number($var) != number($var). It works because NaN never equals NaN, while every number equals itself. Do not abbreviate this to number($var) != $var. That usually works, but fails when $var is an empty node set. A more direct alternative is string(number($var)) = 'NaN'.

EXSLT defines ckbk:lowest as follows:

  • Function ckbk:lowest returns nodes whose values equal the set’s minimum, as calculated by ckbk:min. A node has that minimum when converting its string value through number equals the minimum, using numeric comparison operator =.

  • If any node is non-numeric, function ckbk:min returns NaN. Numeric comparison defines NaN != NaN. Thus any non-numeric node makes ckbk:lowest return an empty node set.

The literal EXSLT implementation may not be efficient:

<xsl:template name="ckbk:lowest">
  <xsl:param name="nodes" select="/.." />
  <xsl:if test="$nodes and not($nodes[number(.) != number(.)])">
    <xsl:variable name="min">
      <xsl:for-each select="$nodes">
        <xsl:sort data-type="number" />
        <xsl:if test="position( ) = 1">
          <xsl:value-of select="number(.)" />
        </xsl:if>
      </xsl:for-each>
    </xsl:variable>
    <xsl:copy-of select="$nodes[. = $min]" />
  </xsl:if>
</xsl:template>

The xsl:if test examines all nodes for non-numeric values, then sorts to find min and gathers every node with that min. The next example also uses ckbk:min without an extra sort.

Example: Lowest using ckbk:min.

<xsl:template name="ckbk:lowest">
  <xsl:param name="nodes" select="/.."/>
  <xsl:variable name="min">
    <xsl:call-template name="ckbk:min">
      <xsl:with-param name="nodes" select="$nodes"/>
    </xsl:call-template>
  </xsl:variable>
  <xsl:choose>
    <xsl:when test="number($min) = number($min)">
      <xsl:copy-of select="$nodes[. = $min]"/>
    </xsl:when>
  </xsl:choose>
</xsl:template>

Finally, implement ckbk:lowest in one pass if you forgo reuse of ckbk:min, as below.

Example: Lowest without reusing ckbk:min.

<xsl:template name="ckbk:lowest">
  <xsl:param name="nodes" select="/.."/>
  <xsl:param name="lowest" select="/.."/>
  <xsl:variable name="index" select="ceiling(count($nodes) div 2)"/>
  <xsl:variable name="aNode" select="$nodes[$index]"/>
  <xsl:choose>
    <xsl:when test="not($index)">
      <xsl:copy-of select="$lowest"/>
    </xsl:when>
    <xsl:when test="number($aNode) != number($aNode)"/>
    <xsl:otherwise>
      <xsl:choose>
        <xsl:when test="not($lowest) or $aNode &lt; $lowest">
          <xsl:call-template name="ckbk:lowest">
            <xsl:with-param name="nodes" select="$nodes[not(. &gt;= $aNode)]"/>
            <xsl:with-param name="lowest" select="$nodes[. = $aNode]"/>
          </xsl:call-template>
        </xsl:when>
        <xsl:when test="$aNode = $lowest">
          <xsl:call-template name="ckbk:lowest">
            <xsl:with-param name="nodes" select="$nodes[not(. &gt;= $aNode)]"/>
            <xsl:with-param name="lowest" select="$lowest|$nodes[$index]"/>
          </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
          <xsl:call-template name="ckbk:lowest">
            <xsl:with-param name="nodes" select="$nodes[not(. &gt;= $aNode)]"/>
            <xsl:with-param name="lowest" select="$lowest"/>
          </xsl:call-template>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

Interestingly, this performs worse, perhaps due to extra copying. With 10,000 data points in sorted, reverse-sorted, semi-random and random distributions, the ckbk:min implementation beat the xsl:sort implementation by about 40% on average, often more. Recursion without ckbk:min was 24% slower than with it.

The ckbk:highest definition and implementations follow by reversing the relational logic of ckbk:lowest, so need no repetition.

XSLT 2.0

XPath 2.0 has built-in min and max functions.

Discussion

Simple XPath expressions for minimum and maximum nodes are <xsl:value-of select="$nodes[not($nodes < .)]"/> and <xsl:value-of select="$nodes[not($nodes > .)]"/>. The first selects nodes for which none is smaller; the second selects nodes for which none is larger.

These simple expressions have complexity O(N2), where N is the node count. Avoid them unless that count is small. Sometimes they are necessary, such as finding min/max within the select attribute of xsl:sort or the use attribute of xsl:key, where no template can be called.

Another XSLT publication called this recursive minimum implementation more efficient than xsl:sort:

<xsl:template name="ckbk:min">
  <xsl:param name="nodes" select="/.."/>
  <xsl:param name="min" select="number('NaN')"/>
  <xsl:choose>
    <xsl:when test="not($nodes)">
      <xsl:value-of select="number($min)"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:variable name="aNode" select="$nodes[1]"/>
      <xsl:call-template name="ckbk:min">
        <xsl:with-param name="nodes" select="$nodes[position( ) &gt; 1]"/>
        <xsl:with-param name="min">
          <xsl:choose>
            <xsl:when test="$aNode &lt; $min or string($min) = 'NaN'">
              <xsl:value-of select="$aNode"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="$min"/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:with-param>
      </xsl:call-template>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

None of my tested XSLT implementations confirms this, and I doubt any would. Eliminating only one node per step likely makes it slower. Even with tail recursion, nodes often need copying. It is easy to mistake this for efficient indexed iteration in C or Java. Indexing differs from creating a new node set by removing the first element through $nodes[position( ) > 1].

Minimum and maximum are often both needed. This code computes both for little extra complexity:

<xsl:template name="ckbk:min-max">
  <xsl:param name="nodes" select="/.."/>
  <xsl:param name="nodes-for-max" select="$nodes"/>
  <xsl:param name="min"/>
  <xsl:param name="max"/>
  <xsl:variable name="count1" select="count($nodes)"/>
  <xsl:variable name="aNode1" select="$nodes[ceiling($count1 div 2)]"/>
  <xsl:variable name="count2" select="count($nodes-for-max)"/>
  <xsl:variable name="aNode2" select="$nodes-for-max[ceiling($count2 div 2)]"/>
  <xsl:choose>
    <xsl:when test="not($count1) and not($count2)">
      <xsl:value-of select="concat(number($min),',',number($max))"/>
    </xsl:when>
    <xsl:when test="number($aNode1) != number($aNode1) and number($aNode2) != number($aNode2)">
      <xsl:value-of select="concat(number($aNode1),',',number($aNode2))"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:call-template name="ckbk:min-max">
        <xsl:with-param name="nodes" select="$nodes[not(. &gt;= number($aNode1))]"/>
        <xsl:with-param name="nodes-for-max" select="$nodes-for-max[not(. &lt;= number($aNode2))]"/>
        <xsl:with-param name="min">
          <xsl:choose>
            <xsl:when test="not($min) or $aNode1 &lt; $min">
              <xsl:value-of select="$aNode1"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="$min"/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:with-param>
        <xsl:with-param name="max">
          <xsl:choose>
            <xsl:when test="not($max) or $aNode2 &gt; $max">
              <xsl:value-of select="$aNode2"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="$max"/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:with-param>
      </xsl:call-template>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

Tests also show this outperforming the sorting-based solution.

So far, nodes themselves have been the numbers. A more general problem finds extrema of a function of those nodes. For positive and negative inputs, for example, find the minimum squared value. Modifying these implementations to square values is easy, but one reusable implementation is preferable. Extending and embedding XSLT revisits this problem and describes alternatives for generic solutions.

  

 

 

 

back to top