listfindpositionnetlogo

Find the first item in a list from the value of an attribute in Netlogo


I am working in Netlogo with a model where each agent has a path through the network. Each node has an attribute called 'mode' with values ["bike" "bus" "train" "u-g"]. I want to find the first myway item that has a different mode from the previous one. For example:

observer> ask turtle 4455 [show myway]
 
turtle 4455 > [(vertex 77445) (vertex 66227) (vertex 39816) (vertex 98972) (vertex 47091) (vertex 88001)]

The correspondence with the modes would be ["bike" "bike" "bike" "bike" "train" "train"], so I would need to find item 4, i.e. the first different mode in the list.

My attempt to solve it is to create a new list with modes for each vertex like this:

ask turtle 4455 [
let mymodes [] 
foreach myway [ r -> 
set mymodes lput [mode] of r mymodes]
show mymodes]

[ "bike" "bike" "bike" "bike" "train" "train"]

I now try to find the position of the first "train" in the list with the commands position and first:

show position (first mymodes != "Bici") mymodes

But it returns "false", and I need the position.

Thanks for your help!


Solution

  • You might try this:

    let f first mymodes
    let tf map [m -> (m = f)] mymodes
    show position false tf
    

    tf is a list of true/false values corresponding to whether each element of mymodes is equal to the first. position then finds the first false value.

    Note that you can create mymodes with map instead of foreach:

    let mymodes map [r -> [mode] of r] myway
    

    map is a very useful primitive.