Thursday, 12 January 2017

Recursion in XSLT

Yesterday I got involved in a question to handle a list of input documents where there is a start value and for every other element this start value has to be increased until an end value is reached.

In more advanced XSLT cases you may end up in a situations that aren't solvable using a for-each. Why not? Well, in the for-each you can't iteratively re-calculate a variable. Like a program language as Scala, XSLT is in fact a so called 'functional' language. Maybe not in the strict sense of the definition (I haven't checked), but one of the definitions is that in a functional language, or at least in Scala, variables are immutable. In XSLT once assigned a value, a variable cannot be changed. So a variable in XSLT is only variable at first assignment.

How to solve this? Well, with recursion. This morning I googled on XSLT and recursion and found this nice explanation.

Recursion is a paradigm in which a certain object or functionality is repeated by itself.

In computer programming this is done by defining a function with a specific implementation of functionality and where before of after that implementation the function calls itself with an altered set of input values until a certain end-condition is reached. It's one of the first computer algorithms I learned in a language as Pascal. And a typical example is calculating the factorial of a natural number.

I use recursion in XSLT regularly, for instance in a template that replaces a string in an another string until all occurrences have been replaced. I wrote about that in 2010 already.

In this blog post I'll omit providing an example, since I already provided a few in the articles linked above. I just want to draw your attention to this concept in XSLT. But if you like to read more on XSLT and recursion, you might be interested in this blog article.


No comments :