我考虑使用(map and reduce)和迭代来实现argmax。
这是我使用map和reduce实现的:
to-report argmax1 [arguments f]
if length arguments = 0 [ show "incorrect length of arguments" report nobody]
report first reduce [ ifelse-value ((last ?1) > (last ?2)) [?1] [?2]] map [(list ? (runresult f ?))] arguments
end
这是我使用迭代实现的。
to-report argmax2 [arguments f]
if length arguments = 0 [ show "incorrect length of arguments" report nobody]
let max-argument first arguments
let max-evaluation runresult f max-argument
foreach arguments
[
let current-evaluation runresult f ?
if current-evaluation > max-evaluation
[
set max-argument ?
set max-evaluation current-evaluation
]
]
report max-argument
end
我的问题是:使用内置函数有什么好处吗?在我的map / reduce代码中,我迭代列表两次,而不是使用map / reduce迭代它一次。在python中,map / reduce会加速,因为它编译为C而不是python字节代码。是否有netlogo的等价物?
思想?
答案 0 :(得分:1)
你可以摆脱map
:
to-report argmax [#args #f]
let _x0 first #args
let _best (list _x0 (runresult #f _x0))
set _best reduce
[update ?1 ?2 #f]
fput _best butfirst #args
report first _best
end
to-report update [#xf #x #f]
let _f0 last #xf
let _f1 (runresult #f #x)
report ifelse-value (_f1 > _f0) [list #x _f1] [#xf]
end
to test ;to illustrate
let _xs n-values 10 [?]
show argmax _xs task [(- ?) * ?]
end