RE: [Camllist] Operator overloading
[
Home
]
[ Index:
by date

by threads
]
[ Message by date: previous  next ] [ Message in thread: previous  next ] [ Thread: previous  next ]
[ Message by date: previous  next ] [ Message in thread: previous  next ] [ Thread: previous  next ]
Date:  20070309 (12:08) 
From:  Andrej Bauer <Andrej.Bauer@f...> 
Subject:  Re: [Camllist] Operator overloading 
To all who like overloading, I dearly suggest that they explain to themselves the following bit of Mathematica: In[1]:= f[v_] = {{1,0}, {1,1}} . (v + {0,1}); In[2]:= f[{0,0}] Out[2]= {{0, 0}, {1, 1}} Firstly, if you do not think about the above, you won't even see what's wrong. Secondly, once you do see what is wrong, you won't know why it's wrong. The problem is caused by the meaning of + and Mathematica evaluation strategy. Explanation of what is wrong: 1) {0,1} is a twodimensional vector 2) {{1,0},{1,1}} is the 2x2 matrix with rows (1,0) and (1,1) 3) The operator . means, according to the help system: In[4]:= ?. a.b.c or Dot[a, b, c] gives products of vectors, matrices and tensors. For example, multiplying a 2x2 matrix and a 2D vector gives a 2D vector: In[5]:= {{1,0},{1,1}} . {0,1} Out[5]= {0, 1} 4) Clearly, + is addition :) but in case you do not trust me: In[6]:= ?+ x + y + z represents a sum of terms. 5) The definition of f then says: take v, add to it the vector {0,1}, then multiply by the 2x2 matrix {{1,0},{1,1}}. 6) Thus we compute f[{0,0}] by hand according to 5): f[{0,0}] = {{1,0},{1,1}} . ({0,0} + {0,1}) = {{1,0},{1,1}} . {0,1} = {0,1} 7) Hmm, strange, Mathematica thinks the answer is a 2x2 matrix, and we think it's a 2D vector. Have fun overloading! I will repeat my suggestion again: when writing serious and complicated code, overloading can cause a lot of harm. When manipulating expressions such as vectors and matrices interactively, it is convenient to have overloaded + etc. Perhaps the right way to solve the dilemma is to have a "toplevel on streoids" which intelligently resolves ambiguities. The intelligence can then go much further than simple overloading. Andrej