user12092724
user12092724

Reputation:

Adding same item to more lists

I need to know if it is possible to add the same item to more than one list a time. Specifically, I want to add items to one turtle's list and to the lists of all the turtles connected to that turtle. Something like this:

set list lput item list (turtle's list)

set list lput item list (neighbours' lists)

The item it's supposed to be the same. You could image a graph: turtles are nodes and each turtle has its own list. My approach was:

ask one-of turtle[
set list lput item list
foreach [in-link-neighbors] of turtles-here
 [  item -> set list lput item list ] 
]

Thank you for your help

Upvotes: 0

Views: 70

Answers (1)

JenB
JenB

Reputation: 17678

Short answer - yes, it is possible.

Here is a complete model with printout so you can see what it is doing.

turtles-own [mylist]

to setup
  clear-all
  create-turtles 10
  [ set color blue
    set mylist (list random 10)
  ]
  ask turtles [ create-links-with n-of 2 other turtles ]
  layout-circle turtles 7
  ask turtles [show mylist]
  ask one-of turtles [add-item-egonet]
  ask turtles [show mylist]
  reset-ticks
end

to add-item-egonet
  let new-value 3
  let targets (turtle-set self link-neighbors)
  ask targets
  [ set color red
    set mylist lput new-value mylist
  ]
end

You didn't say what happened when you tried your code, but you would have received an error because item and list are NetLogo keywords. You also have a logic error - when you ask a turtle, you switch perspective (or 'context' in NetLogo terminology) to that turtle, the subsequent turtles-here will pick up all turtles on that same patch.

The big difference between our approaches is that I have used agentsets rather than lists. It could be done by iterating through a list of turtles, but if you find yourself writing NetLogo code that runs foreach over a list of turtles, the first thing you should do is rethink your approach. There are specific situations where you need lists of turtles, for example if you need to track the sequence of other turtles that a turtle has met. However, unless you are in one of those situations, it is better to use agentsets and ask.

So, switching to the paradigm of agentsets, my code creates the agentset of turtles that I want to change (the selected turtle and its network neighbours) and then simply tells them to add the new value at the end of their own lists of values.

Note that within a model, this could be achieved with a single line by constructing the turtle-set at the same time as asking it, but it would be more typical to do something like (from within an ask so the perspective is that of some selected turtle):

set mylist lput new-value mylist
ask link-neighbors [ set mylist lput new-value mylist ]

Upvotes: 1

Related Questions