I know that we can find the inverse of a function using solve
e.g.
f(x):= a*x+b$
[invf]:solve(f=f(x),x);
However, I haven't been able to work out how to use this in the definition of a new function. I tried a few things, like:
invF(f):=rhs(invf);
but the f
in rhs(invf)
isn't recognized as the argument of the function invF(f)
. Is there any way to define an inverse, or would one simply work with this expression and use something like subst
to evaluate it?
The right-hand side of :=
isn't evaluated (or even simplified), so anything like rhs(invf)
in the function body doesn't actually compute the result until the function is called. What's needed here is to ensure that the result is pasted into the function body at the time the function is constructed.
There are at least two ways to do that. The more general way is to define the function with define
instead of :=
. Then the body is evaluated when the function is defined. E.g. define(invF(x), rhs(inv));
.
Another way which only works at the top level (i.e., not inside any function) is to make use of the so-called quote-quote operator, ''
, which has the effect of interpolating the current value of something into the input, as if it were typed in. E.g. invF(x) := ''(rhs(inv));
.
Quote-quote acts at the time the expression is parsed so that can be surprising if it appears in a function. E.g. y: 123; f(x) := block([y: 2*x], ''y);
then f(4)
returns 123, not 8. That said, I have found quote-quote to be convenient and helpful -- just have to confine it to top-level stuff.