Search code examples
symbolic-mathmaple

Replace Square-Expression in Maple


Given a maple expression like

f := (y + 5)^2 + x^2

How can I replace all occurrences of the square function with a custom function? The result I want to have would be

square(y + 5) + square(x)

I tried something like

subs({x^2 = square(x)}, f)

However, that only replaces the x^2 expression. I could of course list explicitly the (y + 5) term as well, but I want to replace any occurrence of (.)^2 without listing everything explicitly.

How can I do this in Maple?


Solution

  • You can accomplish this using either subsindets or applyrule.

    expression:=(y-5)^2+3+sin(((z-1/3)^2/(t-(y-s)^2)))+F(f(17+p^2)^2);
    
                                       /         2  \                 
                                       |  /    1\   |                 
                                       |  |z - -|   |    /          2\
                            2          |  \    3/   |    | / 2     \ |
       expression := (y - 5)  + 3 + sin|------------| + F\f\p  + 17/ /
                                       |           2|                 
                                       \t - (y - s) /                 
    
    applyrule(_a::anything^2=square(_a), expression);
    
                               /        /    1\  \                               
                               |  square|z - -|  |                               
                               |        \    3/  |
        square(y - 5) + 3 + sin|-----------------| + F(square(f(square(p) + 17)))
                               \t - square(y - s)/                               
    
    
    subsindets(expression, '`^`'(anything,2), u->square(op(1,u)));
    
                               /        /    1\  \                               
                               |  square|z - -|  |                               
                               |        \    3/  |                               
        square(y - 5) + 3 + sin|-----------------| + F(square(f(square(p) + 17)))
                               \t - square(y - s)/