XML technologies / XSLT / XSLT Cookbook / Strings / Reversing a string
(Excerpt from “XSLT Kochbuch” by Sal Mangano)
Problem
You need to reverse a string’s characters.
Solution
XSLT 1.0
This template reverses $input cleverly and efficiently:
<xsl:template name="reverse">
<xsl:param name="input"/>
<xsl:variable name="len" select="string-length($input)"/>
<xsl:choose>
<!-- Strings mit einer Länge kleiner als 2 sind trivial umzukehren -->
<xsl:when test="$len = 2">
<xsl:value-of select="$input"/>
</xsl:when>
<!-- Strings mit der Länge 2 sind ebenfalls trivial umzukehren -->
<xsl:when test="$len = 2">
<xsl:value-of select="substring($input,2,1)"/>
<xsl:value-of select="substring($input,1,1)"/>
</xsl:when>
<xsl:otherwise>
<!-- Tausch der ersten Hälfte und der zweiten Hälfte der Eingabe und rekursive Anwendung dieses Templates -->
<xsl:variable name="mid" select="floor($len div 2)"/>
<xsl:call-template name="reverse">
<xsl:with-param name="input" select="substring($input,$mid+1,$mid+1)"/>
</xsl:call-template>
<xsl:call-template name="reverse">
<xsl:with-param name="input" select="substring($input,1,$mid)"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>XSLT 2.0
Reversal is trivial in 2.0.
<xsl:function name="ckbk:reverse">
<xsl:param name="input" as="xs:string"/>
<xsl:sequence select="codepoints-to-string(reverse(string-to-codepoints($input)))"/>
</xsl:function>Discussion
XSLT 1.0
The solution’s algorithm is not the most obvious, but it is efficient. It reverses even very long strings successfully, whereas more obvious algorithms take too long or overflow the stack. Its basic idea is to swap the string’s two halves, recursively applying the algorithm to each half until only strings of length two or less remain, for which reversal is trivial. The following example illustrates this. At each step, I have put a + where the string was split and concatenated.
reverse(»abcdef«) (input)
reverse(def)+reverse(»abc«)
reverse(»ef«) + »d« + reverse(»bc«) + »a«
»f« + »e« + »d« + »c« + »b« + »a«
fedcba (result)
Studying more obvious XSLT implementations of reverse is instructive: they show how to implement recursive solutions in other contexts, and how not to.
One of the worst algorithms is probably many people’s first attempt: swap the first and last characters, then the second and next-to-last, until reaching the middle. A C programmer might suggest this, since it is an efficient iterative solution in a language allowing random reads and writes of individual string characters and favoring iteration over recursion. In XSLT, however, it must be implemented recursively, as below, without the luxury of modifying variables.
Example: A very poor implementation of reverse.
<xsl:template name="reverse">
<xsl:param name="input"/>
<xsl:variable name="len" select="string-length($input)"/>
<xsl:choose>
<!-- Strings mit einer Länge kleiner als 2 sind trivial umzukehren -->
<xsl:when test="$len < 2">
<xsl:value-of select="$input"/>
</xsl:when>
<!-- Strings der Länge 2 sind ebenfalls trivial umzukehren -->
<xsl:when test="$len = 2">
<xsl:value-of select="substring($input,2,1)"/>
<xsl:value-of select="substring($input,1,1)"/>
</xsl:when>
<xsl:otherwise>
<!-- Verkettung: letztes Zeichen + reverse(mitte) + erstes Zeichen -->
<xsl:value-of select="substring($input,$len,1)"/>
<xsl:call-template name="reverse">
<xsl:with-param name="input" select="substring($input,2,$len - 2)"/>
</xsl:call-template>
<xsl:value-of select="substring($input,1,1)"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>A serious problem makes this solution unsuitable except for very short strings: it is not tail-recursive, as explained under Tail recursion. Many XSLT processors, such as Saxon, optimize tail recursion. Structure your code to benefit from this important optimization. The following example makes this version of reverse tail-recursive by moving only the string’s last character to the front at each call. This puts the recursive call last and exploits the optimization.
Example: An inefficient tail-recursive implementation.
<xsl:template name="reverse">
<xsl:param name="input"/>
<xsl:variable name="len" select="string-length($input)"/>
<xsl:choose>
<!-- Strings mit einer Länge kleiner als 2 sind trivial umzukehren -->
<xsl:when test="$len < 2">
<xsl:value-of select="$input"/>
</xsl:when>
<!-- Strings der Länge 2 sind ebenfalls trivial umzukehren -->
<xsl:when test="$len = 2">
<xsl:value-of select="substring($input,2,1)"/>
<xsl:value-of select="substring($input,1,1)"/>
</xsl:when>
<!-- Verkettung: letztes Zeichen + reverse(rest) -->
<xsl:otherwise>
<xsl:value-of select="substring($input,$len,1)"/>
<xsl:call-template name="reverse">
<xsl:with-param name="input" select="substring($input,1,$len - 1)"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>This change prevents reverse from overflowing the stack, but remains inefficient for large strings. Each step moves only one character, and each call handles a string only one character shorter than the current one. With very large strings, this can overload the implementation’s memory management. While reviewing this recipe, Jeni Tennison suggested another way to make it tail-recursive: pass the remaining string and $len as template parameters. This is generally a good strategy for tail recursion. Here it improved performance, but still did not match the solution.
An important goal in recursive implementations is to make every call handle a subproblem at most half the current problem’s size, so recursion ends sooner. Following this advice gives the next solution for reverse.
Example: An efficient, but not ideal, implementation.
<xsl:template name="reverse">
<xsl:param name="input"/>
<xsl:variable name="len" select="string-length($input)"/>
<xsl:choose>
<xsl:when test="$len < 2">
<xsl:value-of select="$input"/>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="mid" select="floor($len div 2)"/>
<xsl:call-template name="reverse">
<xsl:with-param name="input" select="substring($input,$mid+1,$mid+1)"/>
</xsl:call-template>
<xsl:call-template name="reverse">
<xsl:with-param name="input" select="substring($input,1,$mid)"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>I developed this solution first. It works well even for strings exceeding 1000 characters and is shorter than the implementation under Solution. The only difference is that it treats only lengths zero and one as trivial. The slightly faster implementation halves the recursive calls by also treating length two as trivial.
All these implementations perform the same number of concatenations. I do not think this can be avoided within XSLT. My tests nevertheless show that for a 1000-character string, the best solution is about five times faster than the worst. The two best differ only by a factor of 1.3.
XSLT 2.0
The XSLT 1.0 solution manipulates substrings because it cannot reach the Unicode character level. The 2.0 solution uses functions string-to-codepoints and codepoints-to-string, probably faster in most 2.0 implementations since strings internally are arrays of Unicode integer values.
Tail recursion
A recursive call is tail-recursive if its returned value is immediately returned by the function. “Tail” refers to the call’s position at the end. Tail recursion matters because it can be implemented more efficiently than general recursion, where each call needs a new stack frame for local variables and bookkeeping. General recursion can quickly exhaust the stack with large inputs. Internally, tail-recursive implementations can be converted into iterative solutions by an XSLT processor that recognizes tail recursion.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “XSLT Kochbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de