Re: [xsl] Functional Programming: How do I convert an xsl:for-each loop into a functional style?

Subject: Re: [xsl] Functional Programming: How do I convert an xsl:for-each loop into a functional style?
From: David Carlisle <davidc@xxxxxxxxx>
Date: Thu, 21 Jan 2010 12:53:22 +0000
On 21/01/2010 12:38, Costello, Roger L. wrote:
Hi Folks,

My question is about writing XSLT in a functional programming style.

My understanding is that a litmus test for whether a program is written in a functional style is whether it can be executed in any order.

Consider this problem: convert a sequence of N numbers into a cumulative sequence, in which each number is the sum of the previous numbers.

Here is a loop that solves the problem:

<xsl:for-each select="Number">
       <xsl:value-of select="sum((., preceding-sibling::Number))" />
</xsl:for-each>

Can this code be executed in any order?

Suppose the loop is unraveled into a series of<xsl:value-of> statements. If those statements are evaluated in arbitrary order then the output would not be in the desired sequence. Thus, I conclude, this loop is not written in a functional style. Do you agree?

How would the problem be solved in a functional style?


You are making the mistake of confusing execution order with the order of items in the result tree.


When making an xml result tree the order of the items almost always matters, you do not want the words in your paragraphs to be arbitrarily re-ordered for example.

However, the point about the side effect free model of programming is that the items in that for-each can be executed in any order, and in particular, most importantly these days, in parallel. of course the partial results that come in in arbitrary orders need to be marshalled into the correct output sequence which may or may not be trivial, but in general that's an issue with parallel computing: how to avoid spending longer working out who does what, and how to combine the results, than the time you gain by by having multiple threads.

You say "here is a loop" but xsl:for-each is not a loop in the sense of a C for or fortran do loop. It is a specification how each item in a sequence is to be processed, and an implied specification how all the results are merged. It is not an instruction to process the items in a particular order. And if you add a non side-effect free instruction such as xsl;message into the loop, it is possible that you see that in fact things are not processed in the order you expect.

David


________________________________________________________________________ The Numerical Algorithms Group Ltd is a company registered in England and Wales with company number 1249803. The registered office is: Wilkinson House, Jordan Hill Road, Oxford OX2 8DR, United Kingdom.

This e-mail has been scanned for all viruses by Star. The service is
powered by MessageLabs. ________________________________________________________________________


Current Thread