Search code examples
listf#maxby

F# int list of two maximums


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?


Solution

  • 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