在 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

这将是一个不错的功能。我正在尝试实现一个抽象的本地搜索算法,这对于传递 objective 函数等非常有用。

您不能将函数作为函数传递(我相信),但您当然可以将函数名称作为文本传递,然后使用 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