NetLogo: How to implement a proposal-card (aka `flatMap`)?

NetLogo has a primitive mapthat runs a reporter task for each entry in the input list and collects a list of results.

Many programming languages ​​that have mapone also have something called flatMap(either monadic bindor collector SelectManyor mapcanor append-map)) that does the same, but allows (or requires) a reporter task to report a list of results instead. The end result is a single list containing all result lists concatenated.

In the logo (including NetLogo), the part of concatenation is called sentence, therefore, it may be a good name for an operation combining matching with concatenation sentence-map.

So, for example, we want:

observer> show sentence-map task [list ? ?] [1 2 3]
observer: [1 1 2 2 3 3]

Note that it sentencedoes not require all its entries to be lists. For example, (sentence 1 [2 3] 4)evaluated as [1 2 3 4]. Therefore, our definition sentence-mapwill follow this example. Example:

observer> show sentence-map task [ifelse-value (? mod 2 = 0) [(list ? ?)] [?]] [1 2 3]
observer: [1 2 2 3]

How to implement sentence-mapand is the implementation effective?

+3
source share
1 answer

The easiest way to determine is sentence-mapas follows:

to-report sentence-map [f xs]
  report reduce sentence map f xs
end

In terms of efficiency, if you are using NetLogo 5.0.5 or later, this definition should perform well (O (n) -ish runtime).

NetLogo 5.0.4 sentence O (n 2) - NetLogo ( Scala).

- NetLogo, , sentence, , lput, sentence-map.

+3

All Articles