How do I compute the argmax of a function on a list in Stanza?

66 Views Asked by At

I'd like to know if there is a function to compute the argmax of a function f on a list of numbers (integers, longs, floats) numbers in Stanza.

It would have the following behaviour:

defn argmax (f, numbers: Tuple) :
  val N = length(numbers)
  if N == 0 :
    fatal("Can't compute the argmax of an empty tuple")

  var max-index = 0
  var max-value = numbers[0]

  for idx in 1 to N do :
    val value = f(numbers[idx])
    if value > max-value :
      max-index = idx
      max-value = value
  
  max-index

defn f (x) :
  x * x

println $ argmax(f, [1, 6, 2, 5])

Result :

1

Thank you!

2

There are 2 best solutions below

0
On BEST ANSWER

One way to create argmax is in the functional style as follows:

defn argmax (nums:Tuple<Comparable>) :
  reduce(fn (a, b) : a when (a[1] > b[1]) else b, zip(0 to false, nums))[0]

which applies a pairwise max over a tuple of combined indices and values. To complete the solution, you would use the following:

defn f (x) :
  x * x

defn argmax (f, nums:Tuple<Comparable>) :
  argmax(map(f, nums))
0
On

You can use a pair of functions argmax! and argmax?, which is a common idiom in stanza where a sequence operation might fail (in this case, when the tuple is empty)

For example:

defpackage argmax: 
  import core
  import collections

defn argmax? (vals:Seqable<Comparable>) -> False|Int:
  false when empty?(to-seq(vals)) else argmax!(vals)

defn argmax! (vals:Seqable<Comparable>) -> Int: 
  defn compare (left:[Comparable, Int], right:[Comparable, Int]):
    left when left[0] > right[0] else right
  val [_, argmax] = reduce(compare, zip(vals, 0 to false))
  argmax

val vals = [1, 6, 2, 5]
println("argmax of [%,] is: %_" % [vals, argmax!(vals)])
println("argmax of empty tuple is: %_" % [argmax?([])])

To apply a function to an arbitrary sequence you can use seq

val vals = [1, 6, 2, 5]
defn f (x): 
  x * x
println("argmax of f = %_" % [argmax?(seq(f, vals))])

Type annotations are optional, they're just here for clarity