xsl-list
[Top] [All Lists]

Re: [xsl] Using divide-and-conquer recursion to create a cumulative sequence

2009-12-12 05:11:45
2009/12/11 Costello, Roger L. <costello(_at_)mitre(_dot_)org>:

Hi Folks,

I wish to convert a sequence of N numbers:

  (23, 41, 70, 103, 99, 6)

Into a cumulative sequence, in which each number is the sum of the previous 
numbers:

  (23, 64, 134, 237, 336, 342)


Hi Roger,

Here's a function that recursively processes sequence, with linear performance:


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

<xsl:variable name="seq" select="(23, 41, 70, 103, 99, 6)" as="xs:integer+"/>

<xsl:function name="f:sumSeq" as="xs:integer+">
        <xsl:param name="seq" as="xs:integer+"/>
        <xsl:param name="pos" as="xs:integer"/>
        
        <xsl:sequence select="if ($pos gt count($seq)) then $seq else
                f:sumSeq((subsequence($seq, 1, $pos), $seq[$pos + 1] + 
$seq[$pos],
subsequence($seq, $pos + 2)), $pos + 1)"/>
</xsl:function>

<xsl:template match="/">
        <xsl:value-of select="f:sumSeq($seq, 1)"/>
</xsl:template>

</xsl:stylesheet>


cheers
-- 
Andrew Welch
http://andrewjwelch.com
Kernow: http://kernowforsaxon.sf.net/

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--