I'm trying to write a small script that will look at the first term of an expression and determine whether it is positive or negative, then print a +
or -
in front of that expression, accordingly; however, I'm having a bit of trouble writing it in such a way that it reliably extracts the first term of the expression.
I have been experimenting with part
and args
. I have been leaning towards args
because I haven't found any way to determine the "depth" of parts
for an arbitrary expression (i.e. I'm not sure how one can determine whether to use, e.g. part(expr,1)
or part(expr,1,1)
or part(expr, 1,1,1)
etc.).
The issue with args
is that, e.g.
declare(cos, posfun)$
args(-2*cos(x));
> [2 cos(x)]
i.e. the negative is dropped, presumably due to the lisp representation of the expression (we get the same result from part(-2*cos(x),1)
; moreover, part(-2*cos(x),2)
"falls off the end" -- it seems part
simply can't see the -
).
By contrast,
args(-2*cos(x)+x);
> [x, -2cos(x) ]
as expected.
Regardless of whether or not this is the desired behaviour for these functions, I was hoping to find some way to get around it so that I can have a function that would have the following bevaiour:
addOp(x) > ["+", x]
addOp(-x) > ["-", x]
addOp(1+2*x+x^2) > ["+", 1+2*x+x^2]
addOp(-2+2*x+x^2) > ["-", 2+2*x+x^2] /* NB: only the first term is scaled by -1, not the entire expression */
addOp(cos(...)) > ["+", cos(...)]
addOp(-2x*cos(...)) > ["-", 2x*cos(x) ]
I also tried using the op
function along with a known number; however, the internal representation of negative numbers means that something like op(1-3*cos(x))
returns +
.
This one has had me stumped for a while, so any suggestions would be greatly appreciated.