2

如果我用一个非常高的初始 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
4

2 回答 2

4

如果函数只是返回另一个函数的结果,尾递归就可以工作。在这种情况下,你有primaryColor + traceColorAt(...),这意味着它不仅仅是返回函数的值——它还在向它添加一些东西。

您可以通过将当前累积的颜色作为参数传递来解决此问题。

于 2011-03-12T07:37:43.773 回答
4

递归调用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.

于 2011-03-12T07:39:07.543 回答