Re: Rule and Module not working together
- To: mathgroup at smc.vnet.net
- Subject: [mg77879] Re: Rule and Module not working together
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Tue, 19 Jun 2007 06:31:30 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <f55q32$k02$1@smc.vnet.net>
Steven Siew wrote:
> On Mathematica 5.2, I tried to write a function which applies the rule
> Log[A_] + Log[B_] -> Log[A * B] but somehow it does not work as I
> expected.
>
> Instead of Log[f] + Log[g] becoming Log[f * g], I get the result of
> Log[666 * f] even though I have marked both A and B as private
> variables.
>
> Can anyone help? I'm sure I made a big mistake somewhere in my
> understanding of Mathematica.
>
>
>
> In[1]:= AppendTo[$Echo,"stdout"]
> Out[1]= {stdout}
>
> In[2]:= (* Write your mathematica code below *)
>
> In[3]:= If[Length[Names["Global`*"]] > 0, Remove["Global`*"]]
>
> In[4]:= Off[General::spell, General::spell1]
>
> In[5]:= myfunc[x_] := Module[{s, A, B},
> s = {Log[A_] + Log[B_] -> Log[A*B]}; Return[x /. s]]
>
> In[6]:= ? myfunc
> Global`myfunc
>
> myfunc[x_] := Module[{s, A, B}, s = {Log[A_] + Log[B_] -> Log[A*B]};
> Return[x /. s]]
>
> In[7]:= B = 666;
>
> In[8]:= myfunc[Log[f] + Log[g]]
>
> Out[8]= Log[666 f]
>
> In[9]:= myfunc[Log[4] + Log[5]]
>
> Out[9]= Log[2664]
>
> In[10]:= (* End of mathematica code *)
>
> In[11]:= Quit[];
>
>
Steven,
A transformation rule, defined either by -> or :>, must be applied
thanks to the replacement operators /. (ReplaceAll) or //.
(ReplaceRepeated). You do not need a Module construct to localize a and
b for the rule takes care of that.
myFun[x_] := x //. Log[a_] + Log[b_] :> Log[a*b] //.
Log[a_] - Log[b_] :> Log[a/b]
Below, you can compare several incremental versions of myFun and see by
their returned results in what way they differ.
(* First we try with ReplaceAll /. *)
In[1]:=
myFun[x_] := x /. Log[a_] + Log[b_] :> Log[a*b]
myFun[Log[2] + Log[3]]
Out[2]=
Log[6]
(* OK, but the above failed with more than two logs *)
In[3]:=
myFun[Log[2] + Log[3] + Log[4]]
Out[3]=
Log[4] + Log[6]
(* ReplaceRepeated //. will correct that *)
In[4]:=
myFun[x_] := x //. Log[a_] + Log[b_] :> Log[a*b]
myFun[Log[2] + Log[3] + Log[4]]
Out[5]=
Log[24]
(* Good, but that does not work difference of logs *)
In[6]:=
myFun[Log[2] - Log[3] + Log[4]]
Out[6]=
-Log[3] + Log[8]
(* Adding an extra rule correct that *)
In[7]:=
myFun[x_] := x //. Log[a_] + Log[b_] :> Log[a*b] //.
Log[a_] - Log[b_] :> Log[a/b]
myFun[Log[2] - Log[3] + Log[4]]
Out[8]=
8
Log[-]
3
Regards,
Jean-Marc