MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Re: search for an operator in an expression

  • To: mathgroup at smc.vnet.net
  • Subject: [mg78414] Re: [mg78392] Re: search for an operator in an expression
  • From: Carl Woll <carlw at wolfram.com>
  • Date: Sun, 1 Jul 2007 03:44:50 -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> <200706301005.GAA09186@smc.vnet.net>

Albert wrote:

>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
>  
>
I think it would be simpler to use the pattern a_Plus instead:

In[62]:= expr = 2 + a*Exp[-b x] + Sin[c + b] + d;

In[64]:= Cases[expr, a_Plus :> Length[a] - 1, {0, Infinity}]

Out[64]= {1,3}

Carl Woll
Wolfram Research

>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
>  
>



  • Prev by Date: Re: Graphics package in v6
  • Next by Date: Re: Iterpolation and Dates
  • Previous by thread: Re: Rotable Graphics and ViewPoint
  • Next by thread: Re: search for an operator in an expression