Search code examples
lambdanetlogohigher-order-functions

Run a task with a variable number of arguments in NetLogo


I have a task and a list of arguments. I'd like to apply the task to the list of arguments. Is the only way to do this by using strings instead of tasks and just concatenating? Basically, I'm looking for the equivalent of apply in other languages.


Solution

  • I came across this problem again, and actually figured out a solution!

    to-report listify-task [ tsk num-args ]
      let args (reduce word n-values num-args [ (word " (item " ? " ?)") ])
      report runresult (word "task [ (runresult tsk " args ") ]")
    end
    

    This converts a reporter task from something that takes a number of arguments to one that takes a list. You use it like so:

    observer> show (runresult (listify-task task [?1 + ?2] 2) [4 5])
    observer: 9
    

    apply could be implemented on top of this like:

    to-report apply [ tsk args ]
      report (runresult (listify-task tsk length args) args)
    end
    

    though it would be somewhat inefficient. Better to store the result of listify-task and the run that whenever you need to.

    It essentially creates a task of the following form: task [ (runresult tsk item 0 ? item 1 ? ...)].