Applying operations to each element of the list

I want to split each item in a list by a number, I have tried the following:

Approach 1:

set item 0 (new-vec item 0 vec / number)
set item 1 (new-vec item 1 vec / number)

      

gives an error, this is not something you can use, set to

Approach 2:

 foreach new-vec
[ set ? ? / number]

      

doesn't seem to work.

Please, help. Thanks in advance.

+3


source to share


1 answer


This is because NetLogo lists are immutable data structures.

If you really want mutability, you can always use an extension, but once you learn how to use NetLogo's immutable lists correctly, it is almost never required: enumerating primitives is usually all you need.

To split all the numbers in the list by some other number, use map

:

let new-vec [10 50 100]
let number 10
let divided-vec map [ ? / number ] new-vec

      

will assign the list [1 5 10]

divided-vec

.

The operation map

creates a new list by applying the operation to each element of the list that you pass to it. In the example above, I assigned the new list to the new variable ( divided-vec

), but if you want, you can assign it as well new-vec

:



set new-vec map [ ? / number ] new-vec

      

It will behave as if you changed it new-vec

in place, although it is not.

If you want to apply the operation to only one item in the list, you can do it with a combination of replace-item

and item

:

let my-list [2 4 6 8 10]
show replace-item 1 my-list (item 1 my-list  * 100)

      

will show: [2 400 6 8 10]

+4


source







All Articles