我目前正在自学 F#(通过 try f# 站点)。我有以下(恕我直言)尾递归函数用于一元谓词(int-> bool)的存在量化。
let rec exists bound predicate =
if (bound<0) then false
elif predicate(bound) then true
else exists (bound-1) predicate
现在这个函数也可以写成
let rec exists bound predicate = (bound+1>0) && (predicate(bound) || exists (bound-1) predicate)
但是,第二种实现不是尾递归的。问题是编译器是否会将其优化为尾递归?
更简单(好吧,这有点傻)的例子的情况如何,说
let rec hasNoRoot f =
if (f x = 0) then false
else hasNoRoot (fun x -> f (x+1))
相对
let rec hasNoRoot f = (f 0 <> 0) && (hasNoRoot (fun x-> f(x+1)))
在第二个示例中,为了将函数(实际上是它的描述)识别为尾递归,编译器只需要“知道”为了评估连接,不一定必须评估两个连接。
感谢您的建议