Skip to content

Instantly share code, notes, and snippets.

@wallymathieu
Created September 5, 2018 17:20
Show Gist options
  • Save wallymathieu/a64a7f37d7376daf7420352740b6180a to your computer and use it in GitHub Desktop.
Save wallymathieu/a64a7f37d7376daf7420352740b6180a to your computer and use it in GitHub Desktop.
Maxima and minima
open FSharpPlus
open FSharpPlus.Operators
module Collection=
let inline maximaBy (projection: 'T->'Key) (source: '``Collection<'T>``) : '``Collection<'T>``=
let sorted = sortByDescending projection source
match tryHead sorted with
| None -> sorted
| Some max -> takeWhile ((compare <| projection max) >> (=) 0 << projection) sorted
let inline minimaBy (projection: 'T->'Key) (source: '``Collection<'T>``) : '``Collection<'T>``=
let sorted = sortBy projection source
match tryHead sorted with
| None -> sorted
| Some min -> takeWhile ((compare <| projection min) >> (=) 0 << projection) sorted
module List=
let maxima l=
let sorted = List.sortDescending l
match sorted with
| []|[_] -> sorted
| max::_ -> List.takeWhile ((compare max) >> (=) 0) sorted
let minima l=
let sorted = List.sort l
match sorted with
| []|[_] -> sorted
| min::_ -> List.takeWhile ((compare min) >> (=) 0) sorted
let maximaBy projection l=
let sorted = List.sortByDescending projection l
match sorted with
| []|[_] -> sorted
| max::_ -> List.takeWhile ((compare <| projection max) >> (=) 0 << projection) sorted
let minimaBy projection l=
let sorted = List.sortBy projection l
match sorted with
| []|[_] -> sorted
| min::_ -> List.takeWhile ((compare <| projection min) >> (=) 0 << projection) sorted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment