Pass a function as a parameter in Netlogo

两盒软妹~` 提交于 2021-01-27 13:20:33

问题


In many other programming languages, you can pass a function as an argument to another function and call it from within the function.

Is there anyway to do this in Netlogo?

Such as the following:

;; 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

This would be a nice feature. I'm trying to implement an abstract local search algorithm which this would be nice for passing in objective functions and such.


回答1:


You can pass functions as parameters by creating a task and using the runresult to execute the task.

;; 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:


As of Netlogo 6.0.1, the arrow syntax replaced tasks. The below does the same thing as the accepted answer but with the updated syntax.

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



回答3:


you can't pass the function as a function (I believe), but you can certainly pass the function name as text and then use the runresult primitive to run the function. Messy but doable.



来源:https://stackoverflow.com/questions/36539334/pass-a-function-as-a-parameter-in-netlogo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!