繁体   English   中英

F#中的尾部调用优化

[英]Tail Call Optimization in F#

我真的可以在F#中的尾部调用优化方面提供一些帮助。 我试图解析一个像树的结构,并在每片叶子上执行计算。

我遇到问题的函数是calcLength

type Location = float * float
type Radius = float
type Width = float
type Angle = float

type Primitive =      
        | Circle of Location * Radius
        | Ellipse of Location * Radius * Radius
        | Square of Location * Width * Angle
        | MultiPrimitive of Primitive List

type Primitive with
    member x.Length =
        let rec calcLength x =
            match x with
            | Circle (_,r)      -> System.Math.PI * r * 2.
            | Ellipse (_,r1,r2) -> System.Math.PI * 2. * sqrt(  (r1 * r1 ) + (r2 * r2 ) / 2.)
            | Square (_, w,_)   -> w * 4.
            | MultiPrimitive [] -> 0.
            | MultiPrimitive (head::tail) -> calcLength (MultiPrimitive tail) + (calcLength head)

[<Fact>]
let ``test discriminated unions``() =
    let pattern = MultiPrimitive(
                    [ 
                      MultiPrimitive(
                          [ 
                              MultiPrimitive(
                                  [ 
                                    Square( (10.,10.), 10., 45. );
                                    Circle( (3.,7.), 3. );
                                    Circle( (7.,7.), 3. );
                                    Square( (5.,2.), 3., 45. );
                                  ] );

                            Square( (10.,10.), 10., 45. );
                            Circle( (3.,7.), 3. );
                            Circle( (7.,7.), 3. );
                            Square( (5.,2.), 3., 45. );
                          ] );
                      Square( (10.,10.), 10., 45. );
                      Circle( (3.,7.), 3. );
                      Circle( (7.,7.), 3. );
                      Square( (5.,2.), 3., 45. );
                    ] )

    let r = pattern.Length

我尝试将延续方法与以下方法结合使用:

    let rec calcLength x f =
        match x with
        | Circle (_,r)      -> f() + System.Math.PI * r * 2.
        | Ellipse (_,r1,r2) -> f() + System.Math.PI * 2. * sqrt(  (r1 * r1 ) + (r2 * r2 ) / 2.)
        | Square (_, w,_)   -> f() + w * 4.
        | MultiPrimitive [] -> f()  
        | MultiPrimitive (head::tail) -> calcLength head (fun () -> calcLength(MultiPrimitive tail) f )

    calcLength x (fun () -> 0.)

但步进通过与调试器显示堆栈越来越大,任何帮助将非常感激。

使用CPS的通常方法是将结果传递给给定的延续:

        let rec calcLength x k =
            match x with
            | Circle (_,r)      -> k (System.Math.PI * r * 2.)
            | Ellipse (_,r1,r2) -> k (System.Math.PI * 2. * sqrt(  (r1 * r1 ) + (r2 * r2 ) / 2.))
            | Square (_, w,_)   -> k (w * 4.)
            | MultiPrimitive [] -> k 0.
            | MultiPrimitive (head::tail) -> (calcLength head (fun h -> calcLength(MultiPrimitive tail) (fun t -> k (h + t))))

因此在MultiPrimitive情况下,您需要传递另一个延续来处理计算头部的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM