我正在尝试编写一个小脚本,该脚本将查看表达式的第一项并确定它是正数还是负数,然后相应地在该表达式前面打印一个+
或;-
但是,我在编写它时遇到了一些麻烦,它可以可靠地提取表达式的第一项。
我一直在试验part
和args
。我一直倾向于,args
因为我还没有找到任何方法来确定parts
任意表达式的“深度”(即我不确定如何确定是否使用,例如 part(expr,1)
or part(expr,1,1)
orpart(expr, 1,1,1)
等)。
问题args
是,例如
declare(cos, posfun)$
args(-2*cos(x));
> [2 cos(x)]
即否定被丢弃,大概是由于表达式的 lisp 表示(我们从 得到相同的结果part(-2*cos(x),1)
;此外,part(-2*cos(x),2)
“从末尾掉下来”——似乎part
根本看不到-
)。
相比之下,
args(-2*cos(x)+x);
> [x, -2cos(x) ]
正如预期的那样。
不管这是否是这些函数所期望的行为,我都希望找到某种方法来解决它,以便我可以拥有一个具有以下行为的函数:
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) ]
我还尝试使用该op
函数和一个已知数字;然而,负数的内部表示意味着类似op(1-3*cos(x))
返回+
。
这个让我难倒了一段时间,所以任何建议都将不胜感激。