MathGroup Archive 2005

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

Search the Archive

Re: Checking for a given phrase in an expression

  • To: mathgroup at smc.vnet.net
  • Subject: [mg60773] Re: [mg60744] Checking for a given phrase in an expression
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Wed, 28 Sep 2005 01:41:12 -0400 (EDT)
  • References: <200509270745.DAA18926@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On 27 Sep 2005, at 16:45, lost.and.lonely.physicist at gmail.com wrote:

> Hello everyone
>
> Is it possible to ask Mathematica to check if a given phrase occurs in
> an expression? Say I have
>
> aa = 1 + x + x y + Log[Sin[z]]
>
> and
>
> bb = x + Log[Sin[z]]
>
> Can Mathematica tell me such a phrase bb exists in aa? Can it tell me
> its 'position' within the expression aa?
>
> Thanks for the help!
>
>


Your question is actually  too vague to have an unambiguous answer.  
One can define a function like this:

SubExpressionQ[a_, b_] := Block[{f}, (a /. b -> f) =!= a]

This will test if something is a "subexpression' of something else in  
the sense of Matheamtica's pattern matching. Thus in your case:


aa = 1 + x + x*y + Log[Sin[z]]; bb = x + Log[Sin[z]];


SubExpressionQ[aa, bb]


True


However, this concept of subexpression will not necessarily always  
correspond to what you might expect. For example just take

s = (x/y)^2

You might expect that x/y is a subexpression ("phrase") of s, but in  
fact:


SubExpressionQ[s,x/y]

False

To understand why you need to look at the FullForm of the two  
expressions:


FullForm[s]

Times[Power[x,2],Power[y,-2]]


FullForm[x/y]

Times[x,Power[y,-1]]

and now you can see why one is not a "phrase" in the other. As I  
wrote at the beginning, the meaning of "phrase in something"is  
ambiguous. There are various ways to interpret it. One way is the  
above, which is based on the way Mathematica evaluates and represents  
expressions. Another possible approach would be to convert both  
expressions to strings and use Mathematica's string matching  
abilities to  test if the two expressions convert to substrings of  
one another. This approach will of course not always agree with the  
other.
Given all that there is also no clear sense in which you can speak of  
a "position" of one expression in anohter, particularly that the  
commutative and associative laws for addition and multiplication are  
used in pattern matching .

Andrzej Kozlowski









  • Prev by Date: Re: N-nested For loops, with N variable - Best way to implement?
  • Next by Date: Re: Checking for a given phrase in an expression
  • Previous by thread: Re: Re: Checking for a given phrase in an expression
  • Next by thread: Re: Checking for a given phrase in an expression