如何在 xpath 表达式中实现具有名称的用户定义函数?

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

我正在使用 XSLT。我知道 Inline Function Expressions,有什么方法可以在 xpath 表达式中声明命名函数吗?因为我需要函数名来实现递归调用。

在 XSLT 中,我只是建议使用 xsl:function,因为这样你的函数就有一个名字,你可以在函数体内递归地调用它。

至于纯 XPath 3,Dimitre 几年前在 https://dnovatchev.wordpress.com/2012/10/15/recursion-with-anonymous-inline-functions-in-xpath-3-0-2/ 中使用 let 和高阶函数(不幸的是 Saxon 9 HE 不支持该功能)探索了这条路径,我认为他的那里的代码使用的函数类型语法与最终规范不太一致,因此他的示例需要

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)

可以缩短为

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)

我想考虑到最新允许的语法。

无法在 XPath 中声明命名函数; XPath 3.1 只允许匿名内联函数,并且这些函数不能递归。有人告诉我,有一种方法可以使用一种称为 Y 组合器的技术在匿名函数中实现递归,但它相当令人难以置信,我从来没有想过它。正如 Martin 所建议的,您最好的方法是将这部分逻辑放在 XSLT 级别。