F# int list of two maximums

181 Views Asked by At

Previous question: F# Filtering multiple years

I need to return an int list of two years where the given years are the greatest amount of rainfall for any February within the data set.

So far, I have found the first year using List.maxBy but I believe this will only ever return the first maximum.

let rainfall
    ds |> List.filter (fun s-> month(s)=2)
       |> List.maxBy rain
       |> year

So how do I show both the first and second?

2

There are 2 best solutions below

3
On BEST ANSWER

You should probably sort them descending:

let rainfall
    ds |> Seq.filter (fun s-> month(s)=2)
       |> Seq.sortBy (fun m -> -(rain m)) //Sort by the value of rain negated
       |> Seq.take 2
       |> Seq.toList

And then just take the first 2.

This will give you a list 2 items, the one with the most rainfall and the one with the second most.

If you want them as separate values you can do:

let most = ds |> List.nth 0
let secondMost = ds |> List.nth 1
0
On

Use List.sort providing function that would sort by rain descending and take first 2 elements