Re: search for an operator in an expression
- To: mathgroup at smc.vnet.net
- Subject: [mg78392] Re: search for an operator in an expression
- From: Albert <awnl at arcor.net>
- Date: Sat, 30 Jun 2007 06:05:10 -0400 (EDT)
- References: <f5iuqu$a99$1@smc.vnet.net> <f5o8jr$5jo$1@smc.vnet.net> <f5qhdc$2jt$1@smc.vnet.net> <f5tcb1$2ir$1@smc.vnet.net> <f62k8u$bp5$1@smc.vnet.net>
Hi,
>> you must distinguish between OutputFormat, what you see, and FullForm,
>>
>> what Mathematica sees. Try: FullForm[yourExpression] then you will see
>>
>> that you have 1 operator Plus with multiple arguments. If you want to
>>
>> see the number of arguments, you could e.g. use:
>>
>> Cases[expression, Plus[x__] :> Length[x]]
while in principle this shows the principle of the in my opinion
clearest way how to treat this, it does not work here and the nearely
correct result is just an accident, as you can see when you check what
the matches really are:
In[17]:= Cases[expr, Plus[x__] :> XXX[x]]
Out[17]= {XXX[2], XXX[d], XXX[a \[ExponentialE]^(-b x)],
XXX[Sin[b + c]]}
you must be careful for these reasons:
- Plus has Attributes that influence pattern matching in a way that is
not what we need here, among them Flat and Orderless.
- Cases looks for matches by Default only in level 1, to find all
instances you need to explicitly tell it to.
- Plus[a,b] is a+b, so the number of plus signs in StandardForm is one
less than the length of the arguments of the corresponding Plus
- x matches a Sequence in the above code, which Length does not really
like
Taking account of all these, the following should work for arbitrary
expressions, although I did not really test it...
In[14]:= Total[
Cases[expr /. Plus -> plus,plus[x__] :> (Length[{x}]-1),{0,Infinity}]
]
Out[14]= 4
By the way it is always a good idea to check whether pattern matching
constructs really do what you want, in this case the following makes me
believe I could be right :-)
In[19]:= Cases[expr /. Plus -> plus,plus[x__] :> XXX[x], {0,Infinity}]
Out[19]= {XXX[b, c], XXX[2, d, a Exp[-b x], Sin[plus[b, c]]]}
hope that works and helps,
albert