I am new to F# and writing some simple algorithm to get used to the language, which needs argMax
. Does the standard library come with a function for searching for a list element that maximizes a function? That is, if there's an existing function that behaves like this one:
let argMax f xs =
let rec go a fa zs =
match zs with
| [] -> a
| z :: zs' ->
let fz = f z
if fz > fa
then go z fz zs'
else go a fa zs'
match xs with
| [] -> invalidArg "xs" "empty"
| x :: xs' -> go x (f x) xs'
Yes, but it's called List.maxBy
.
Here's an example:
let f x = -(x * x) + 100 * x + 1000
List.maxBy f [0..1000]
// val it : int = 50
f 50
// val it : int = 3500
There is also List.minBy
and the same functions are available for Seq
and Array
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With