Reduce、Map 和迭代:效率

Reduce, Map, and Iterations: Efficiency

我正在考虑使用(map 和 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 的等效项?

想法?

你可以去掉 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