Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the F# library has a standard function for `argMax`?

Tags:

f#

argmax

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'
like image 369
Alex Avatar asked Oct 04 '15 18:10

Alex


Video Answer


1 Answers

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.

like image 199
Gus Avatar answered Sep 18 '22 21:09

Gus