I am unable to replace dot by *.
Replace[a.a, .-> *]
Is there any solution to get this done?
I am unable to replace dot by *.
Replace[a.a, .-> *]
Is there any solution to get this done?
You can use ReplaceAll (/.)
:
a.a /. Dot -> Times
a^2
Alternatively, you can temporarily redefine Dot
as Times
using Block
:
Block[{Dot = Times}, a.a]
a^2
I think there are several reasonons pointed out by Szabolcs in the comments why the approach failed, and they are not all supper basic by my standard. I would like to point them out.
First the basics
foo -> bar
is the same thing as Rule[foo,bar]
and the same thing as foo~Rule~bar
.
This underlying expression is often hidden and not important, but checking the underlying description is very helpful when debugging. Check out FullForm
and TreeForm
.
The second argument .-> *
is not a valid syntax
When parsing this input, the interpreter expects .
, ->
and *
to be infix operators. Having two or more infix operators next to each other can not be interpreted and it is indicated by codehighlighting of the cell:
It effectivly reads:
(~Dot~) (~ReplaceAll~) (~Times~)
which can not be interpreted, as left and right operands are missing.
Also ToExpression[".->*"]
returns a message
ToExpression::sntx: Invalid syntax in or before
".->*"
.
Repalce checks only the top level
Repalce will not replace a part of an expression. Compare:
In[1953]:=
Replace[Dot, Dot -> Times]
Replace[Dot[a.a], Dot -> Times]
Replace[Dot[a.a], Dot[a.a] -> Times[a a]]
Out[1953]= Times
Out[1954]= a.a
Out[1955]= a^2
Working solutions
Either use more general replacement rule:
In[1939]:= Replace[a.b, (f_).(g_) :> (f*g)]
Out[1939]= a b
or instead of Replace
use a ReplaceAll
(/.
) , which tries to apply the pattern also to subexpressions:
In[1943]:=
FullForm[a.b]
ReplaceAll[a.b, Dot -> Times]
FullForm[%]
Out[1943]//FullForm=
Dot[a,b]
Out[1944]=
a b
Out[1950]//FullForm=
Times[a, b]
a.a /. Dot -> Times
? $\endgroup$ – kglr Sep 19 '18 at 8:03Replace
documentation (it operates at level 0 by default).Reaplce
effectively works on theFullForm
of expressions, not code strings. $\endgroup$ – Szabolcs Sep 19 '18 at 8:04FullForm
is useful to check what an expression really is. $\endgroup$ – Αλέξανδρος Ζεγγ Sep 19 '18 at 9:23Replace
thing is important to get it working, but it is really just a practical detail, not a conceptual point. $\endgroup$ – Szabolcs Sep 19 '18 at 13:52