NetLogo: break out of nested foreach loop

Viewed 1382

I'm trying to break out of a nested foreach loop using 2 lists of sorted turtles. But instead of just leaving the inner loop, netlogo breaks out of the whole procedure. I have a code like the one below (this one is made up, but has exactly the same structure):

to do-something    
  let xturtles sort-by [ [a b] -> [birthday] of a > [birthday] of b ] turtles
  ;; construct an ordered set
  foreach xturtles [ the-xturtle ->
    ask the-xturtle [
      let xage birthday
      let yturtles sort-by [ [a b] -> [birthday] of a > [birthday] of b ] turtles with [birthday < xage] 
       ;; construct a second ordered set
      foreach yturtles [ the-yturtle ->
        let breakout-condition? false
        ask the-yturtle [
          if (hidden? ) [
            set breakout-condition? true
          ]
        ]
        if breakout-condition? [ stop ]
      ]
    ]
  ]
end

However, when the stop condition is reached, netlogo breaks out of the whole procedure, instead of continuing with the outer loop (the xturtles loop)?

Is that the expected behavior? If so, what is a good practice in this case?

Thanks! Felix

1 Answers

It looks even nesting the stop within an extra ask procedure in the same procedure doesn't help. However, if you need a quick fix I think you can replace the second foreach loop with a standalone procedure that contains the stop as a workaround. For example, this procedure follows a similar format to yours and the same problem comes up- as soon as stop is called the broader foreach is exited.

to nest-foreach-example
  ca
  crt 1
  let xs [ 1 2 3 4 ]
  let ys [ 1 2 3 4 ]
  foreach xs [ 
    x ->
    foreach ys [ 
      y ->
      ask turtles [
        if y > x [
          stop
        ]
      ]
      print word x y 
    ]
  ]
end

This prints out 11.

However, if you make a custom procedure to take the place of your "y" foreach loop, it works (with or without the ask turtles):

to nest-foreach-example-turtles
  ca
  crt 1
  let xs [ 1 2 3 4 ]
  let ys [ 1 2 3 4 ]
  foreach xs [ 
    x ->
    for-y x ys 
  ]

end

to for-y [ x_ ys ]
  foreach ys [
    y ->
    ask turtles [
      if y > x_ [
        stop
      ]
    ]
    print word x_ y
  ]
end

Outputs:

11
21
22
31
32
33
41
42
43
44
Related