To make it tail-recursive, make the recursive call the last operation in the function.

https://en.wikipedia.org/wiki/Tail_call

The else() clause is what keeps it from being tail recursive.  Something like this should work:

declare variable $bookstore := <bookstore>
 
<book>
   
<name>story</name>
   
<price>50.00</price>
   
<author>smith</author>
 
</book>
 
<book>
   
<name>history</name>
   
<price>150.00</price>
   
<author>kelly</author>
 
</book>
 
<book>
   
<name>epic</name>
   
<price>300.00</price>
   
<author>jones</author>
 
</book>
</bookstore>;

declare function local:sum($books, $sum)
{
   
let $sum :=  $sum + $books[1]/price
   
return (
       
<price>{ $sum }</price>,
       
$books[2] ! local:sum(tail($books), $sum)
    )
}
;

<prices>
{
   
local:sum($bookstore/book, 0)
}
</prices>



Jonathan

On Mon, Feb 18, 2019 at 10:24 AM Giuseppe G. A. Celano <celano@informatik.uni-leipzig.de> wrote:
I am writing a recursive function which is similar to the one here:

https://stackoverflow.com/questions/27702718/to-add-values-in-cumulative-format

Interestingly, local:sum() works if there are not many <book/>. However with 38000 book element I get the error "Stack Overflow: Try tail recursion".

Any idea?

Ciao,
Giuseppe