带守卫尾的函数是递归的吗
Are functions with guards tail recursive
我想知道带有守卫的函数是否可以尾递归。例如,给定 elem
的实现
elem' :: (Eq a) => a -> [a] -> Bool
elem' x [] = False
elem' x (y:ys)
| x == y = True
| otherwise = elem' x ys
这个尾部是递归的吗?我会说是的,但不知何故我不相信。
是的,是尾递归
“尾递归”在 Haskell 上下文中的含义的一个可能定义是对“连接点”的调用是有效的,因为它们可能只出现在 tail-recursive 位置。
在 Compiling without Continuations 的第 3 页,我们找到这个数字:
我们看到 case 语句中的 right-hand-side 个备选方案是 tail-call 个位置。我们也可以在 GHC 源码中找到对应的代码。
连同 desugaring of guards according the Haskell report,它告诉我们守卫本质上是嵌套的 case
-表达式,我们可以得出结论,您的函数是 tail-recursive.
(尽管应该说“elem'
是 tail-recursive 作为两个参数的函数”——没有指定元数,这个问题就没有意义了。)
我想知道带有守卫的函数是否可以尾递归。例如,给定 elem
的实现
elem' :: (Eq a) => a -> [a] -> Bool
elem' x [] = False
elem' x (y:ys)
| x == y = True
| otherwise = elem' x ys
这个尾部是递归的吗?我会说是的,但不知何故我不相信。
是的,是尾递归
“尾递归”在 Haskell 上下文中的含义的一个可能定义是对“连接点”的调用是有效的,因为它们可能只出现在 tail-recursive 位置。 在 Compiling without Continuations 的第 3 页,我们找到这个数字:
我们看到 case 语句中的 right-hand-side 个备选方案是 tail-call 个位置。我们也可以在 GHC 源码中找到对应的代码。
连同 desugaring of guards according the Haskell report,它告诉我们守卫本质上是嵌套的 case
-表达式,我们可以得出结论,您的函数是 tail-recursive.
(尽管应该说“elem'
是 tail-recursive 作为两个参数的函数”——没有指定元数,这个问题就没有意义了。)