Piotr Zurek
Piotr Zurek

Reputation: 2879

Sorting tuples in F#

I have a list of tuples representing coordinates of points. How can I sort them by the first or second value, so that I could order my points from left to right first and from top to bottom next?

Upvotes: 6

Views: 1693

Answers (3)

Brian
Brian

Reputation: 118865

Sounds like you want e.g.

myList |> List.sortBy fst

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Collections.List.html

But tuples support structural equality and comparison, so the default sort (lexicographical) may do what you want.

Upvotes: 6

gradbot
gradbot

Reputation: 13862

Side Note:

This isn't about sorting but if your using tupled coordinates you may want to use a Set instead of a List. Using a Set really helped me to simplify my implementation of Tetris.

Upvotes: 2

Codingday
Codingday

Reputation: 855

 let sorted = List.sort_by (fun (a,b) -> a,b) myList

Change the a,b if you need the other way around

Upvotes: 1

Related Questions