[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
5.4.2 Matching parts of expressions
A more general way to look for patterns in expressions is provided by the member function
bool ex::has(const ex & pattern); |
This function checks whether a pattern is matched by an expression itself or by any of its subexpressions.
Again some examples in ginsh
for illustration (in ginsh
,
has()
returns ‘1’ for true
and ‘0’ for false
):
> has(x*sin(x+y+2*a),y); 1 > has(x*sin(x+y+2*a),x+y); 0 (This is because in GiNaC, "x+y" is not a subexpression of "x+y+2*a" (which has the subexpressions "x", "y" and "2*a".) > has(x*sin(x+y+2*a),x+y+$1); 1 (But this is possible.) > has(x*sin(2*(x+y)+2*a),x+y); 0 (This fails because "2*(x+y)" automatically gets converted to "2*x+2*y" of which "x+y" is not a subexpression.) > has(x+1,x^$1); 0 (Although x^1==x and x^0==1, neither "x" nor "1" are actually of the form "x^something".) > has(4*x^2-x+3,$1*x); 1 > has(4*x^2+x+3,$1*x); 0 (Another possible pitfall. The first expression matches because the term "-x" has the form "(-1)*x" in GiNaC. To check whether a polynomial contains a linear term you should use the coeff() function instead.) |
The method
bool ex::find(const ex & pattern, lst & found); |
works a bit like has()
but it doesn't stop upon finding the first
match. Instead, it appends all found matches to the specified list. If there
are multiple occurrences of the same expression, it is entered only once to
the list. find()
returns false if no matches were found (in
ginsh
, it returns an empty list):
> find(1+x+x^2+x^3,x); {x} > find(1+x+x^2+x^3,y); {} > find(1+x+x^2+x^3,x^$1); {x^3,x^2} (Note the absence of "x".) > expand((sin(x)+sin(y))*(a+b)); sin(y)*a+sin(x)*b+sin(x)*a+sin(y)*b > find(%,sin($1)); {sin(y),sin(x)} |