Xslt sum of absolute values

J

Juho Jussila

Hi

I'm trying to calculate sum of absolute values using Xslt 1.0
and math:abs (http://www.exslt.org/math/functions/abs/index.html)

I thought this would work:
<xsl:value-of select="sum(math:abs(/A/B/C))"/>
Well it doesn't, because there are multiple C's.

Is there any nice trick how to do this, or do I have to use
for-each -loop?

Thanks in advance
 
P

Pavel Lepin

Juho Jussila said:
I'm trying to calculate sum of absolute values using Xslt
1.0 and math:abs

I thought this would work:
<xsl:value-of select="sum(math:abs(/A/B/C))"/>
Well it doesn't, because there are multiple C's.

Is there any nice trick how to do this,

None that I know of. sum() wants a nodeset. math:abs() only
works with numbers.
or do I have to use for-each -loop?

xsl:for-each is not a loop and won't help you one bit. You
cannot carry your state (accumulator-to-date or
whatchamacallit) over to the next iteration - because,
effectively, there are no iterations. No guaranteed
order-of-execution. No side effects. Stateless. Keep that
in mind. Always.

What you want is a named templated template that would
recursively abs-sum your nodeset. Use either divide &
conquer, which would mean (*screeching sounds of trying to
remember what little of computational complexity theory I
ever knew*) log N-deep recursion, which is just fine for
most applications, or tail recursion (if your processor is
capable of optimising it away - Dimitre Novatchev posted a
link to his investigations of this matter some time ago).
 
D

David Carlisle

Juho said:
Hi

I'm trying to calculate sum of absolute values using Xslt 1.0
and math:abs (http://www.exslt.org/math/functions/abs/index.html)

I thought this would work:
<xsl:value-of select="sum(math:abs(/A/B/C))"/>
Well it doesn't, because there are multiple C's.

Is there any nice trick how to do this, or do I have to use
for-each -loop?

Thanks in advance

sum(/A/B/C[. &gt; 0]) - sum(/A/B/C[. &lt; 0])

David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top