rng = Random.new(1)
arr = [6, 0]
arr[p rng.rand(2)] += 1
p arr
Output in Ruby (correct):
1
[6, 1]
Output in Crystal:
1
0
[6, 7]
As you can guess, my innocent arr[rand(2)] += 1 has turned into arr[rand(2)] = arr[rand(2)] + 1
me too stepped on this ...
def foo
puts "here"
1
end
arr = [1, 2, 3, 4]
arr[foo] += 1
p arr
Output:
here
here
[1, 3, 3, 4]
Oops!
Right now a += b is rewritten to a = a + b, always. This is fine for variables, but for methods and indexing we should store the right-hand side first to a temporary variable.
Well, the RHS isn't a problem, the _indexing expression_ should be temped in x[index_expr] += other_expr.
Lovely refactorization! Mutations away from parsing, and into normalizer. :-)
Most helpful comment
Lovely refactorization! Mutations away from parsing, and into normalizer. :-)