In BOO, we can easily assign something like:
a, b = b, a + b
a and b are assigned in two independent branches, without side effects. In languages like C#, we often have to use temporary variables to garantee isolation.
A friend of mine just, Tiago Epifânio, posted a comment referring a pretty cool way to do it without the temporary variable:
b = a + (a = b);
Oops, wrong again. 2 years latter I had to rewrite it to:
b = a + (a = b) - a;
<update>
This usage is not as fun as the swap snippet Tiago gave us on his first comment - given the right order and a subtle variable substitution, the branches don't side effect; apart from readability, note that we could always express it like:
a = b;
</update>
Now that we're talking about isolation, it seems to me that BOO is actually doing something like:
Oops, clumsy... The question is: is there a clean and simple way to express "a, b = b, a + b" in C#?Stack<int> stack = new Stack<int>(2);
stack.Push(b);
stack.Push(a + b);
b = stack.Pop();
a = stack.Pop();
1 comment:
Here are several examples, in various languages
Post a Comment