Just sharing some of my inconsequential lunch conversations with you... RSS  

Sunday, September 30, 2007

Fibonacci revisitated

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;

b = a + a;
</update>

Now that we're talking about isolation, it seems to me that BOO is actually doing something like:

Stack<int> stack = new Stack<int>(2);

stack.Push(b);

stack.Push(a + b);

b = stack.Pop();

a = stack.Pop();



Oops, clumsy... The question is: is there a clean and simple way to express "a, b = b, a + b" in C#?

1 comment:

paipo said...

Here are several examples, in various languages

Development Catharsis :: Copyright 2006 Mário Romano