如何比较Fsharp的ResizeArray?

时间:2017-08-06 08:52:15

标签: f#

如何按功能比较排序:cmp?

type Point =
    {
        x : float
        y : float
    }

let s = ResizeArray<Point>()

s.Add{x=1.1 ; y=1.1}
s.Add{x=2.2 ; y=2.2}
s.Add{x=3.3 ; y=3.3}
s.Add{x=2.2 ; y=2.0}

let cmp (A:Point) (B:Point) = 
    A.x + A.y < B.x + B.y

s.Sort()

//s.Sort() 
s |> printfn("%A")

这个结果,但功能不正确:cmp

   seq [{x = 1.1;
         y = 1.1;}; {x = 2.2;
                     y = 2.2;}; {x = 2.2;
                                 y = 2.0;}; {x = 3.3;
                                             y = 3.3;}]

我尝试使用 sortWith ,但仍然不正确。你能帮我解决一下吗?

type Point =
    {
        x : float
        y : float
    }

let s = ResizeArray<Point>()

s.Add{x=1.1;y=1.1}
s.Add{x=2.2;y=2.2}
s.Add{x=1.0;y=1.0}

let cmp (A:Point) (B:Point) =
    if (A.x+A.y) >= (B.x+B.y) then 1
    else 0

List.sortWith cmp s |> List.iter (fun x -> printfn("%f %f\n") x.x x.y)

1 个答案:

答案 0 :(得分:6)

您必须为您的类型提供Comparison delegate

s.Sort(fun a b -> a.x + a.y - b.x - b.y |> int)