“Tasks” in NetLogo 5.0beta1
March 21, 2011
What are tasks?
chunks of code to be run once,run repeatedly, passed around,
stored in variables, etc.
Known elsewhere as
closures
first-class functions
lambda
Tasks in NetLogo 5.0
2 new data types
3 new primitives
8 primitives altered
2 new data types
Command tasks
Reporter tasks
3 new primitives
task
is-command-task?
is-reporter-task?
6 altered primitives
map, filter, reduce,
n-values, sort-by
foreach
2 more altered primitives
run
runresult
NOT altered (for now)
ifelse, while, repeat, loop, ...
NOT altered (for now)
ask, of, with, all?, ...
Backward compatible syntax
square brackets
inputs: ?1 (aka ?), ?2, ?3, ...
Implicit task syntax
map [? * ?] [1 2 3] => [1 4 9]
filter [? mod 2 = 0] [1 2 3 4] => [2 4]
foreach sort turtles [ print ? ]
Explicit task syntax
set next-task task [ fd 1 ]
set coloring task [ ifelse-value (wealth > 100) [ red ] [ blue ] ]
Disambiguation of task type
command or reporter?look at first token after the opening
bracket (skipping left parens)
No tasks “escape”
unless you use the explicit syntax
Running tasks
run task [ print 5 ]
=> 5
print runresult task [5]
=> 5
Running tasks (variadic)
let printer task [ print ?1 + ?2 ]
(run print 2 3)
=> 5
let square task [? * ?]
print (runresult square 5)
=> 25
Concise task syntax
task die short for task [ die ]
task fd short for task [ fd ? ]
task + short for task [?1 + ?2]
Concise + implicit syntax
map abs [1 -2 3 -4] => [1 2 3 4]
reduce + [1 2 3 4] => 10
filter is-number? [1 “x” 3] => [1 3]
Extra inputs are ignored
(runresult task [? * 2] 1 10 100)=> 2
Tasks are closures
close over procedure inputs
close over local variables
Closing over procedure inputs
to-report printer [x]
report task [ print x ]
end
run printer 5
=> 5
Closing over local variables
let x 5
let y task [ print x ]
run y
=> 5
Close over bindings, not values
let x 5
let y task [x]
set x 10
print runresult y
=> 10
Current agent not closed over
globals [g]
ask turtle 0 [ set g task [ print who ] ]
ask turtle 1 [ run g ]
=> 1
Nonlocal exits
stop and report refer to dynamically enclosing procedure, not enclosing task
(backwards compatible)
It’s fast
100x faster than compiling a string
Models using explicit tasks
State Machine ExampleTermites 3D
(afraid that’s all at the moment)
Use tasks, not strings!
but, still need strings with run/runresult for running code
entered by end user
Possible future work:named inputs
[x => x * x]
(or something like that?not sure yet)
Possible future work:complex reporter tasks
task [
let x ...
...
report ...
]
Wouldn’t it be cool if?:automatic updating
set label task [energy]
set color task [ifelse-value (wealth < 100)
[red] [blue] ]
Wouldn’t it be cool if?:scheduling
in-ticks 5 task [ fd 1 ]
Questions?
http://groups.yahoo.com/group/netlogo-users