Different languages have different behaviors for a loop over a list that modifies the list itself:

JavaScript:


var l = [16]
l.forEach(function(x) {
    var p = x / 2
    if (l.indexOf(p) < 0) {
        l.push(p)
    }
})
l

[16, 8] is returned (results are the same using for-in loop). Newly-added item (8) is not iterated over. PHP acts in the similar way.

Python:

l = [16]
for x in l:
    p = x/2
    if p not in l:
        l.append(p)
l

[32, 16, 8, 4, 2, 1, 0] is returned. Newly-added items are iterated over. Ruby acts in the similar way.

Scala:

val l = MutableList(16)
for (x <- l) {
    val p = x/2
    if (!(l contains p)) { 
        l += p 
    }
}
l

A list of (32, 16, 8) is returned (as of Scala 2.10.4) (results are the same using .foreach). I cannot think of any reason that Scala does this.

:(

标签: scala, python, javascript

添加新评论