如何计算 Stanza 列表中函数的 argmax?
How do I compute the argmax of a function on a list in Stanza?
我想知道是否有一个函数可以计算 Stanza 中数字列表(整数、长整数、浮点数)numbers
上函数 f
的 argmax。
它将具有以下行为:
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
谢谢!
创建 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))
您可以使用一对函数 argmax!
和 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))])
类型注释是可选的,它们只是为了清楚起见
我想知道是否有一个函数可以计算 Stanza 中数字列表(整数、长整数、浮点数)numbers
上函数 f
的 argmax。
它将具有以下行为:
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
谢谢!
创建 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))
您可以使用一对函数 argmax!
和 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))])
类型注释是可选的,它们只是为了清楚起见