0

我想知道是否有一个函数可以计算 Stanza 中f的数字列表(整数、长整数、浮点数)上的函数的 argmax numbers

它将具有以下行为:

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])

结果 :

1

谢谢!

4

2 回答 2

0

一种创建方法argmax是功能样式,如下所示:

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

max它对组合索引和值的元组应用成对。要完成解决方案,您将使用以下内容:

defn f (x) :
  x * x

defn argmax (f, nums:Tuple<Comparable>) :
  argmax(map(f, nums))
于 2021-02-25T16:37:10.153 回答
0

您可以使用一对函数argmax!and argmax?,这是序列操作可能失败的节中的常见习惯用法(在这种情况下,当元组为空时)

例如:

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?([])])

要将函数应用于任意序列,您可以使用seq

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

类型注释是可选的,它们只是为了清晰起见

于 2021-02-25T16:55:18.220 回答