RE: [xsl] Please help me if u can. XSLT functional programming

Subject: RE: [xsl] Please help me if u can. XSLT functional programming
From: Jarno.Elovirta@xxxxxxxxx
Date: Tue, 3 Jun 2003 09:57:46 +0300
Hi,

> Now I am used to programming Java etc. I was schocked to 
> notice that it is
> not possible to change variables. I am used to recursion in 

Who'd want to change variables anyway...

> Well I have heard of the Xalan Extensions etc, which allow 
> assigning new
> values to variables. I guess this would be a workaround. But 

You don't want to go there.

> in so many postings that this is no nice style, besides its being
> proprietary. So can anybody please help me to write a nice recursive
> stylesheet that can do this? Any hints? Please.

E.g.

  <xsl:template match="EQUATION">
    <RESULT>
      <xsl:copy-of select="ID"/>
      <VALUE>
        <xsl:apply-templates select="EXPRESSION"/>
      </VALUE>
    </RESULT>
  </xsl:template>
  <xsl:template match="EXPRESSION">
    <xsl:apply-templates select="*"/>
  </xsl:template>
  <xsl:template match="MULTI | PLUS">
    <xsl:variable name="arg1">
      <xsl:apply-templates select="*[1]"/>
    </xsl:variable>
    <xsl:variable name="arg2">
      <xsl:apply-templates select="*[2]"/>
    </xsl:variable>
    <xsl:choose>
      <xsl:when test="self::MULTI">
        <xsl:value-of select="$arg1 * $arg2"/>
      </xsl:when>
      <xsl:when test="self::PLUS">
        <xsl:value-of select="$arg1 + $arg2"/>
      </xsl:when>
    </xsl:choose>
  </xsl:template>
  <xsl:template match="NUMBER">
    <xsl:value-of select="."/>
  </xsl:template>

or

  <xsl:template match="EQUATION">
    <RESULT>
      <xsl:copy-of select="ID"/>
      <VALUE>
        <xsl:apply-templates select="EXPRESSION"/>
      </VALUE>
    </RESULT>
  </xsl:template>
  <xsl:template match="EXPRESSION">
    <xsl:apply-templates select="*">
      <xsl:with-param name="arg1">
        <xsl:apply-templates select="*/*[1]"/>
      </xsl:with-param>
      <xsl:with-param name="arg2">
        <xsl:apply-templates select="*/*[2]"/>
      </xsl:with-param>
    </xsl:apply-templates>
  </xsl:template>
  <xsl:template match="NUMBER">
    <xsl:value-of select="."/>
  </xsl:template>
  <xsl:template match="PLUS">
    <xsl:param name="arg1" />
    <xsl:param name="arg2" />
    <xsl:value-of select="$arg1 + $arg2"/>
  </xsl:template>
  <xsl:template match="MULT">
    <xsl:param name="arg1" />
    <xsl:param name="arg2" />
    <xsl:value-of select="$arg1 * $arg2"/>
  </xsl:template>

The above stylesheet fragments assume that an operand always has two arguments, though it'll be easy for you to write one that does n number of arguments. The Net is full of calculators written in XSLT. Alltheweb for them.

Cheers,

Jarno - Real Synthetic Audio <http://synthetic.org/play.html>

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


Current Thread