user8278702
user8278702

Reputation:

How to compare in ResizeArray at Fsharp?

How to Sort s by funtion compare : 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")

And this's result , but it's not correct with function : 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;}]

I tried using sortWith but it still not correct . Can you help me to fix ?

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)

Upvotes: 2

Views: 383

Answers (1)

J&#252;rgen H&#246;tzel
J&#252;rgen H&#246;tzel

Reputation: 19727

You have to provide a Comparison delegate for your type:

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

Upvotes: 6

Related Questions