RE: [xsl] How smart are the XSLT processors? Are there any XSLT processors that convert tree-recursive functions into efficient iterative procedures?

Subject: RE: [xsl] How smart are the XSLT processors? Are there any XSLT processors that convert tree-recursive functions into efficient iterative procedures?
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Wed, 28 Apr 2010 11:13:09 +0100
> This task, in fact, raises a different question about 
> generator functions.
> Consider a hypothetic function ex:fibonacci($Fn-1, $Fn-2) 
> that returns an infinitive sequence of fibonacci numbers.
> To use it, one just accesses its result sequence by index.
> 
> <xsl:function name="ex:fibonachi" as="xs:integer*">
>   <xsl:param value="Fn-1" as="xs:integer"/>
>   <xsl:param value="Fn-2" as="xs:integer"/>
> 
>   <xsl:variable name="Fn" as="xs:integer" select="$Fn-1 + $Fn-2"/>
> 
>   <xsl:sequence select="$Fn"/>
>   <xsl:sequence select="ex:fibonachi($Fn, $Fn-1)"/> </xsl:function>
> 
> Honestly, I'm not entirely sure if it's a legal technique in 
> xslt, but definitely it's not supported in saxon, and it 
> would be good if it were supported, as it allows separation 
> of iterator and iteration logic.

Actually this one does work in Saxon: the stylesheet

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
     xmlns:ex="http://example/com/";
xmlns:xs="http://www.w3.org/2001/XMLSchema";
     exclude-result-prefixes="ex xs">

<xsl:template match="/">
<out n="{ex:fibonachi(1,1)[8]}"/>
</xsl:template>

<xsl:function name="ex:fibonachi" as="xs:integer*">
  <xsl:param name="Fn-1" as="xs:integer"/>
  <xsl:param name="Fn-2" as="xs:integer"/>

  <xsl:variable name="Fn" as="xs:integer" select="$Fn-1 + $Fn-2"/>

  <xsl:sequence select="$Fn"/>
  <xsl:sequence select="ex:fibonachi($Fn, $Fn-1)"/> 
</xsl:function>


</xsl:stylesheet>

produces the output <out n="55"/>. 

This works because Saxon evaluates the result of the function lazily.
However, neither the XSLT specification nor the Saxon implementation makes
any guarantees about when evaluation is done lazily, so you can't rely on
this working.

Regards,

Michael Kay
http://www.saxonica.com/
http://twitter.com/michaelhkay 

Current Thread