4

Very basic question, I can't see why my foreach code doesn't do anything (no error message but no effect whatsoever). So my turtles have a 3-dimensionnal variable (intention) that is preset to [0 0 0]. My final problem is much more complex than this, but in simple terms I am now trying to get every dimension of this vector to change to one, that is [1 1 1].

I have created a procedure called change-intention that uses foreach to produce this, to no effect:

to change-intention
ask turtles [
    (foreach intention [ x -> set x 1])
    ]
end

I have tried this on the observer & turtle command line as well as on individual turtles' to no results nor errors..

Thanks!

lomper
  • 379
  • 1
  • 12

1 Answers1

5

Several problems. The first is that lists are not mutable - if you want to change the value in a list, you have to create a new list with that value. The second is that you can't use set to do that, you have to use replace-item.

The code is self contained - open a new model and try it out, changing the call in the testme procedure to different implementations. The procedure change-intention1 is the way you are currently thinking about it (my interpretation anyway). The procedure change-interpretation2 is the way to implement your approach, replacing each item and creating the new list (addressing the problems identified).

However, a better way to do this is with the map procedure instead of foreach because all the values are changed at once rather than looping through the list and dealing with each. Of course, that may not be so easy to implement in your real model.

turtles-own [intention]

to testme
  clear-all
  create-turtles 1
  [ set intention [0 0 0]
  ]
  ask turtles [ type "before call:" print intention ]
  change-intention2
  ask turtles [ type "after call:" print intention ]
  reset-ticks
end

to change-intention1
ask turtles
[ foreach intention
  [ x ->
      print "here"
      set intention 1
  ]
]
end

to change-intention2
ask turtles
[ foreach intention
  [ x ->
      let pp position x intention
      type "here:" print pp
      set intention replace-item pp intention 1
  ]
]
end

to change-intention3
ask turtles
[ set intention map [ x -> 1 ] intention
]
end
JenB
  • 17,620
  • 2
  • 17
  • 45
  • Thanks again @JenB, this works fine - I've tested it as you wrote it as well as in my own model. I knew map would be a more efficient way but could never find the right syntax. I copy yours as well as the precisions regarding lists, `replace-item` and `foreach` :) – lomper Jul 09 '19 at 15:05