Sorting list of tuples f#
Asked Answered
M

3

6

this should be really quick, I have a list of tuples like [("8585", 1);("9232",1);etc] where the second item corresponds to the number of ocurrences the item in "" makes. I was wondering how could i arrange my list from the one that makes more ocurrences to the one that makes least.

f#!

Murphey answered 19/8, 2014 at 18:9 Comment(6)
What's your problem? What's keeping you from running it through a sort function?Stunk
Do you want an answer in any specific language?Bosco
I used List.sortby snd and it sorted from the one with least appearences to the one with most..I needed the other way aroundMurphey
sorry, i am using f#Murphey
Many sort implementations allow you to specify the order, usually through a boolean argument that takes true for ascending or false for descending. If not, you'll just have to reverse the list.Stunk
i tried using List.foldback but it didnt work. should i specify something because they are tuples?Murphey
E
8

Use sortBy:

let lst = [("8585", 1);("9232",3)]
List.sortBy (fun (_, y) -> -y) lst
Effortful answered 19/8, 2014 at 18:18 Comment(0)
P
4

Like Gustavo implied, if it's numeric, you can negate it to reverse its order in sorting. That's what the unary operator ~- is for.

Your peculiar choice of data, that is tuples of 'something * int, let me suspect that you are counting the number of certain occurences, and for that Seq.countBy may help (sorry, no list equivalent).

// Your key, Some data 
[  "9232",   false
   "8585",   false
   "9232",   true 
   "9232",   true ]
|> Seq.countBy fst
|> Seq.sortBy (snd >> (~-))

// val it : seq<string * int> = seq [("9232", 3); ("8585", 1)]

That's sorted by the count (snd element of the tuple) of the key (fst element of the tuple) negated.

Provincetown answered 19/8, 2014 at 18:44 Comment(0)
B
1

F# does have List.sortByDescending, so you could have:

[("8585", 1);("9232",3)]
|> List.sortByDescending (fun (_,y) -> y)
Brueghel answered 4/10, 2021 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.