Re: Recursion in XPath 3.1 inline function definition

Am 29.03.2025 um 15:39 schrieb Dimitre Novatchev:
> There is a way to use recursion with anonymous (inline) functions in
> pure XPath 3, and I reported it in my blog and at the Balisage 2013
> conference.
> Since then, I have built my own, pure XPath 3.1 function libraries
> using this technique.
>
> Here is a simple example:
>
> let $fact-base := function($n as xs:integer,
>                    $f1 as function(xs:integer,
>                    function(*)) as xs:integer
>                    ) as xs:integer
>              {if($n eq 0)
>                  then 1
>                  else $n * $f1($n -1, $f1)
>
>               },
>     $Fact := function($n as xs:integer) as xs:integer
>             {
>                 $fact-base($n, $fact-base)
>             }
>
>    return
>            $Fact(5)
>
> One can run it with BaseX or with Oxygen, or directly online with
> BaseX Fiddle: https://fiddle.basex.org/.


XPath 3.1 online evaluation is also possible at the SaxonJS powered
XPath 3.1 fiddle <https://martin-honnen.github.io/xpath31fiddle/>,
example fiddle
<https://martin-honnen.github.io/xpath31fiddle/?xpath=let+%24fact-base+%3A%3D+function%28%24n+as+xs%3Ainteger%2C%0D%0A+++++++++++++++++++%24f1+as+function%28xs%3Ainteger%2C%0D%0A+++++++++++++++++++function%28*%29%29+as+xs%3Ainteger%0D%0A+++++++++++++++++++%29+as+xs%3Ainteger%0D%0A+++++++++++++%7Bif%28%24n+eq+0%29%0D%0A+++++++++++++++++then+1%0D%0A+++++++++++++++++else+%24n+*+%24f1%28%24n+-1%2C+%24f1%29%0D%0A%0D%0A++++++++++++++%7D%2C%0D%0A++++%24Fact+%3A%3D+function%28%24n+as+xs%3Ainteger%29+as+xs%3Ainteger%0D%0A++++++++++++%7B%0D%0A++++++++++++++++%24fact-base%28%24n%2C+%24fact-base%29%0D%0A++++++++++++%7D%0D%0A%0D%0A+++return%0D%0A+++++++++++%24Fact%285%29&input=&input-type=None>,
and the CheerpJ and Saxon 12 powered XML workbench
<https://martin-honnen.github.io/cheerpj3-saxonhe12-fiddle/>, example
fiddle
<https://martin-honnen.github.io/cheerpj3-saxonhe12-fiddle/?code=let+%24fact-base+%3A%3D+function%28%24n+as+xs%3Ainteger%2C%0D%0A+++++++++++++++++++%24f1+as+function%28xs%3Ainteger%2C%0D%0A+++++++++++++++++++function%28*%29%29+as+xs%3Ainteger%0D%0A+++++++++++++++++++%29+as+xs%3Ainteger%0D%0A+++++++++++++%7Bif%28%24n+eq+0%29%0D%0A+++++++++++++++++then+1%0D%0A+++++++++++++++++else+%24n+*+%24f1%28%24n+-1%2C+%24f1%29%0D%0A%0D%0A++++++++++++++%7D%2C%0D%0A++++%24Fact+%3A%3D+function%28%24n+as+xs%3Ainteger%29+as+xs%3Ainteger%0D%0A++++++++++++%7B%0D%0A++++++++++++++++%24fact-base%28%24n%2C+%24fact-base%29%0D%0A++++++++++++%7D%0D%0A%0D%0A+++return%0D%0A+++++++++++%24Fact%285%29&input=&code-type=XPath&input-type=None>.

Received on Saturday, 29 March 2025 14:52:54 UTC