为什么这个F#内部函数不是尾递归的?

如果我用非常高的初始currentReflection值调用此函数,我会得到一个堆栈溢出异常,这表明该函数不是尾递归的(正确吗?)。我的理解是,只要递归调用是函数的最终计算,那么它应该被编译器优化为尾递归函数以重用当前堆栈帧。有谁知道为什么这不是这里的情况?
let rec traceColorAt intersection ray currentReflection =
        // some useful values to compute at the start
        let matrix = intersection.sphere.transformation |> transpose |> invert
        let transNormal = matrix.Transform(intersection.normal) |> norm
        let hitPoint = intersection.point

        let ambient = ambientColorAt intersection
        let specular = specularColorAt intersection hitPoint transNormal
        let diffuse = diffuseColorAt intersection hitPoint transNormal
        let primaryColor = ambient + diffuse + specular

        if currentReflection = 0 then 
            primaryColor
        else
            let reflectDir = (ray.direction - 2.0 * norm ((Vector3D.DotProduct(ray.direction, intersection.normal)) * intersection.normal))
            let newRay = { origin=intersection.point; direction=reflectDir }
            let intersections = castRay newRay scene
            match intersections with
                | [] -> primaryColor
                | _  -> 
                    let newIntersection = List.minBy(fun x -> x.t) intersections
                    let reflectivity = intersection.sphere.material.reflectivity
                    primaryColor + traceColorAt newIntersection newRay  (currentReflection - 1) * reflectivity
    
已邀请:
traceColorAt
的递归调用显示为更大表达式的一部分。这可以防止尾调用优化,因为在返回
traceColorAt
之后需要进一步计算。 要将此函数转换为尾递归,可以为
primaryColor
添加额外的累加器参数。对
traceColorAt
的最外部调用将传递
primaryColor
(黑色?)的“零”值,并且每个递归调用将在其计算的调整中求和,例如,代码看起来像:
let rec traceColorAt intersection ray currentReflection primaryColor
...
let newPrimaryColor = primaryColor + ambient + diffuse + specular
...
match intersections with
    | [] -> newPrimaryColor
    | _ ->
        ...
        traceColorAt newIntersection newRay ((currentReflection - 1) * reflectivity) newPrimaryColor
如果您希望隐藏来自调用者的额外参数,请引入一个帮助函数来执行大部分工作并从
traceColorAt
调用它。     
如果函数只返回另一个函数的结果,则尾递归有效。在这种情况下,你有
primaryColor + traceColorAt(...)
,这意味着它不仅仅是返回函数的值 - 它还向它添加了一些东西。 您可以通过将当前累积的颜色作为参数传递来解决此问题。     

要回复问题请先登录注册