Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a user-defined function with a name in the xpath expression?

I am using XSLT. I know the Inline Function Expressions, Is there some way to declare a named function in xpath expression? because I need the function name to implement a recursive call.

like image 227
cmf41013 Avatar asked Dec 22 '25 03:12

cmf41013


1 Answers

In XSLT I would simply suggest to use xsl:function as that way your function has a name and you can call it recursively inside of the function body.

As for pure XPath 3, Dimitre explored that path some years ago in https://dnovatchev.wordpress.com/2012/10/15/recursion-with-anonymous-inline-functions-in-xpath-3-0-2/ using let and higher-order functions (a feature not supported unfortunately in Saxon 9 HE), I think his code there uses a function type syntax not quite aligned with the final spec so his example would need to be

let $f := 
    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)

    },
    $F := function($n as xs:integer) as xs:integer {
        $f($n, $f)
    }
return $F(5)

which could be shortened to

let $f := 
    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)

    },
    $F := $f(?, $f)
return $F(5)

I think given the latest allowed syntax.

like image 93
Martin Honnen Avatar answered Dec 23 '25 23:12

Martin Honnen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!