5

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'
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Alex
  • 1,184
  • 7
  • 15

1 Answers1

9

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.

Gus
  • 25,839
  • 2
  • 51
  • 76