xsl-list
[Top] [All Lists]

Re: how to optimize recursive algorithm?

2003-11-27 07:16:55
For instance, say you have a source document like this:

<top>
    <a/>
    <b/>
    <c/>
    <d/>
</top>

and the output of "b" depends on the position of "a", "c" depends on "b" and
so on.

Functional languages are good at expressing loops.

<xsl:template name="position">
 <!-- get results of previous computations via parameters -->
  <xsl:param name="prev-x"/><xsl:param name="prev-y"/>

 <!-- compute current values based on the current node and results computed for 
the previous one -->
  <xsl:variable name="x" select="$prev-x + @width"/>
  <xsl:variable name="y" select="$prev-y + @height"/>

 <!-- output the current node with the results computed -->
  <xsl:copy>
    <xsl:copy-of select="@*">
    <xsl:attibute name="x"><xsl:value-of select="$x"/></xsl:attribute>
    <xsl:attibute name="y"><xsl:value-of select="$y"/></xsl:attribute>
  </xsl:copy>

 <!-- call the template for the next sibling, if there is one -->
  <xsl:for-each select="following-sibling::*[1]">
    <xsl:call-template name="position">
      <xsl:with-param name="prev-x" select="$x"/>
      <xsl:with-param name="prev-y" select="$y"/>
    </xsl:call-template>
  </xsl:for-each>

</xsl:template>

 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list