在Netlogo中将函数作为参数传递

4
在许多其他编程语言中,您可以将一个函数作为参数传递给另一个函数,并在函数内部调用它。在Netlogo中是否有这样的方法呢?例如以下内容:
;; x,y,z are all ints
to-report f [x y z]
  report x + y + z
end

;; some-function is a function
;; x y and z are ints
to-report g [some-function x y z]
  report (some-function x y z) + 2
end

to go
  show g f 1 2 3
end

这将是一个不错的特性。我正试图实现一种抽象的本地搜索算法,这将有助于传递目标函数等内容。
3个回答

5

您可以通过创建任务并使用runresult来执行任务,将函数作为参数传递。

;; x,y,z are all ints
to-report f [x y z]
  report x + y + z
end

;; some-function is a function
;; x y and z are ints
to-report g [some-function x y z]
  report (runresult some-function x y (z + 2))
end

to go
  show g (task f) 1 2 3
end

2
请参阅http://ccl.northwestern.edu/netlogo/docs/programming.html#tasks,了解更多关于任务的信息。 - Seth Tisue

4

从Netlogo 6.0.1开始,箭头语法替换了tasks。下面的代码使用更新的语法实现了与已接受答案相同的功能。

to-report f [x y z]
  report x + y + z
end

;; some-function is a function
;; x y and z are ints
to-report g [some-function x y z]
  report (runresult some-function x y (z + 2))
end


to go
  show g [[x y z] -> (f x y z)] 1 2 3
end

1

我认为你不能将函数作为函数传递,但你可以将函数名称作为文本进行传递,然后使用runresult原语来运行该函数。虽然有些混乱,但可行。


谢谢您的建议;然而,在您的帮助下,我已经找到了解决方案。您不应该在字符串上运行结果,而是可以将函数转换为任务,并在具有适当输入的任务上运行结果,这样效果更好。 - mattsap

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接