leafo / moonscript

:crescent_moon: A language that compiles to Lua
https://moonscript.org
3.18k stars 190 forks source link

Minor evaluation issue regarding update operators #97

Open exists-forall opened 11 years ago

exists-forall commented 11 years ago
foo[bar] += baz

compiles to

foo[bar] = foo[bar] + baz

although it should be

do
    local _update_table_0 = foo
    local _update_index_0 = bar
    _update_table_0[_update_index_0] = _update_table_0[_update_index_0] + baz
end

My intuition tells me that, in addition to other "principle of least surprise advantages", this would improve efficiency for situations such as

multidimensional_array[expensive_row_calculation!][expensive_column_calculation!] += some_value
fillest commented 11 years ago

Why?

exists-forall commented 11 years ago

Because expensive_row_calculation! and expensive_column_calculation! would only have to be calculated once, not twice. Also, is the multidimensional_array is sparse, the hashing of expensive_row_calculation! would only have to be performed once to get the column array.

exists-forall commented 11 years ago

Also, there's a convention within macro-like systems (of which moonscript is one) that expressions should be evaluated only as many times as they are written. For example, python's neat

a < b < c

syntax (which is basically a macro, albeit a language level one, in that it is a syntactic shortcut) is not exactly equivalent to

a < b and b < c

because b is only evaluated once in the first case.

exists-forall commented 11 years ago

Again, this is very minor. It's a small detail, and it doesn't really matter if it's addressed. I just thought it would be worthwhile to bring it up because there are situations where it makes a noticeable difference which form it the update compiles to.

fillest commented 11 years ago

Ah, I posted my question before you edited your post :) Yeah, for multidimensional it's handy. But for single- it can theoretically bring some overhead (copying numbers?), so better use it only for multidimensional

leafo commented 11 years ago

Yeah this is definitely a bug. I'd like to fix this.