地图任务中的局部变量?

Local variable in map task?

有没有办法在 map 的内联报告任务中定义局部变量?

这个

to go
  show map [? * ?] [1 2 3]
end

显示 [1 4 9],正如预期的那样。第一组括号中的是 "reporter task".

如果我想在任务中使用let怎么办?

to go
  show map [
             let sq ? * ?
             sq + 1
           ]
           [1 2 3]
end

错误:"Expected a reporter task here, rather than a list or block."整个第一个括号内的表达式被突出显示为产生语法错误的内容。

也许我需要添加 task 关键字来告诉 NetLogo 这是一个任务?编程指南说 "the task primitive is optional" 代表 map 但值得一试。这有效:

to go
  show map (task [? * ?]) [1 2 3]
end

但这不是:

to go
  show map (task [
                   let sq ? * ?
                   sq + 1
                 ])
           [1 2 3]
end

sq 的第二个实例被突出显示,并显示错误消息 "Expected command." 奇怪的是这次的错误不同。

也许我需要添加 report?

to go
  show map (task [
                   let sq ? * ?
                   report sq + 1
                 ])
           [1 2 3]
end

这在语法上是可以接受的,但是当我 运行 它时,我得到一个 运行 时间错误:"MAP expected input to be a reporter task but got the command task (command task from: procedure GO) instead."

我发现唯一可行的替代方法是定义一个单独的报告器:

to go
  show map square-plus-one [1 2 3]
end

to-report square-plus-one [n]
  let sq n * n
  report sq + 1
end

这很简单。但是,我很好奇我是否遗漏了什么。有没有办法在内联记者任务中使用局部变量?

目前无法完成具有复杂记者的记者任务。请参阅编程指南中的“限制”部分,在“Tasks”下:

Reporter tasks can't contain commands, only a single reporter expression.

https://github.com/NetLogo/NetLogo/issues/351 是相关的——它专门讨论了需要从外部范围引用 ? 变量的问题。