Sponsored

XSLT Reference

fold-left()

XSLT 3.0 higher-order function

Accumulates a result by applying a function left-to-right over a sequence, starting from an initial zero value.

Syntax
fold-left(sequence, zero, function)

Description

fold-left() (also called a left reduce) processes a sequence from left to right. It begins with an initial accumulator value (zero) and repeatedly applies a binary function that takes the current accumulator and the next item, producing the new accumulator. The final accumulator value is the result.

Parameters

ParameterTypeRequiredDescription
sequenceitem()*YesThe sequence to fold over.
zeroitem()*YesThe initial accumulator value.
functionfunction(item(), item()) as item()YesA binary function: (accumulator, currentItem) → newAccumulator.

Return value

item()* — the final accumulated value after processing all items.

Examples

Summing a sequence of numbers

Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <result>
      <xsl:variable name="nums" select="(1, 2, 3, 4, 5)"/>
      <sum>
        <xsl:value-of select="fold-left($nums, 0, function($acc, $x) { $acc + $x })"/>
      </sum>
      <product>
        <xsl:value-of select="fold-left($nums, 1, function($acc, $x) { $acc * $x })"/>
      </product>
    </result>
  </xsl:template>
</xsl:stylesheet>

Output:

<result>
  <sum>15</sum>
  <product>120</product>
</result>

Building a string from a sequence

Input XML:

<?xml version="1.0" encoding="UTF-8"?>
<tags>
  <tag>xslt</tag>
  <tag>xpath</tag>
  <tag>xml</tag>
</tags>

Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/tags">
    <result>
      <xsl:value-of select="fold-left(
        tag[position() gt 1],
        string(tag[1]),
        function($acc, $t) { $acc || ', ' || string($t) }
      )"/>
    </result>
  </xsl:template>
</xsl:stylesheet>

Output:

<result>xslt, xpath, xml</result>

Notes

  • fold-left() processes items in sequence order (left to right). For right-to-left, use fold-right().
  • If the sequence is empty, the zero value is returned unchanged.
  • The accumulator can be any XDM value, including maps, arrays, or sequences.
  • For array-based folding, use array:fold-left().

See also