繁体   English   中英

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

[英]Pass a function as a parameter in Netlogo

在许多其他编程语言中,您可以将函数作为参数传递给另一个函数,并在函数内调用它。

无论如何在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

这将是一个很好的功能。 我正在尝试实现一个抽象的局部搜索算法,这对于传递目标函数等很有用。

您可以通过创建任务并使用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

从Netlogo 6.0.1开始,箭头语法取代了任务。 下面的内容与接受的答案相同,但使用了更新的语法。

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

你不能将函数作为函数传递(我相信),但你当然可以将函数名称作为文本传递,然后使用runresult原语来运行该函数。 凌乱但可行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM