6.5. Miltiple sum, or quantity times price

Calculating sum of calculations is an example of a popular task with a poor XSLT solution. Let's demonstrate it on a quantity times price. A part of a source XML:

Example 19. Items with price and quantity

<item price="20" qty="2"/>
<item price="30" qty="1"/>
<item price="40" qty="4"/>

The task is to calculate the sum of each (price*qty). XSLT FAQ provides a solution (section "Math", subsection "Quantity times price"), which takes 25 lines and uses recursion. As result, the code is hard to understand.

Compare the XSLT solution and the XSieve solution:

Example 20. XSieve solution for quantity times price

(apply + 
  (map (lambda (node)
    (* (x:eval "number(@qty)"   node)
       (x:eval "number(@price)" node)))
    (x:eval "//item")))

Code is easily read and understood by those who know Scheme. The "map" function takes list of all "item" elements, applies an anonymous lambda-function to each item, and returns the results as list, which in turn is processed by "+".