8
$\begingroup$

I was trying to define a function f such that, when its second argument is negative, we have $$ f(a,b,c,d,\dots,n)=f(a,-b,-c,-d,\dots,-n) $$ i.e., we reverse the sign of everything except for its first argument. The shortest code I could come up with is

f[a_, b__] /; Negative[{b}[[1]]] := -f[a, Sequence @@ Minus /@ {b}]

which is admittedly not very clean (is there a better approach?).

But anyway, for fun, my first attempt was

f[a_, b__] /; Negative[{b}[[1]]] := f[a, -b]

which I didn't really expect to work. Much to my surprise, this code does not throw any errors, but it does not really do what I want:

f[1, -2, 3, 4]
(* f[1, 24] *)

which means that $$ f(a,b,c,d,\dots,n)=f(a,-bcd\cdots n) $$

What is going on here? I thought that -b would be interpreted as -(-2,3,4) (which, as I expected, throws an error). But Traceing it, it seems that it is interpreted as -(-2)*3*4. Why?

$\endgroup$
  • 2
    $\begingroup$ check -b // FullForm $\endgroup$ – kglr Jul 1 at 13:27
  • 1
    $\begingroup$ @kglr ugh...${}{}$ $\endgroup$ – AccidentalFourierTransform Jul 1 at 13:30
11
$\begingroup$
ClearAll[foo]
foo[a_, b_?Negative, c___] := foo[a, -b, Sequence @@ (-{c})]

foo[1, -2, 3, -4, 5, 6]

foo[1, 2, -3, 4, -5, -6]

For something that also works with symbolic arguments you can use Internal`SyntacticNegativeQ instead of Negative:

ClearAll[foo2]
foo2[a_, b_?Internal`SyntacticNegativeQ, c___] := foo2[a, -b, Sequence @@ (-{c})]

foo2[1, -r, s, -t, u, v]

foo2[1, r, -s, t, -u, -v]

foo2[1, -2, 3, -4, 5, 6]

foo2[1, 2, -3, 4, -5, -6]

What is happening?:

- b // FullForm

Times[-1, b]

3 Sequence[a, b, c]

3 a b c

$\endgroup$
  • $\begingroup$ It seems the OP has accepted this answer, but with the way I read it, wouldn’t we want the -b to remain -b? Everything else I agree with, nice methods and explanation, too! $\endgroup$ – CA Trevillian Jul 3 at 5:14
  • 1
    $\begingroup$ @CATrevillian, OP says when b is negative $f(a,b,c,d,\dots,n) = f(a,-b,-c,-d,\dots,-n)$, "i.e., we reverse the sign of everything except for its first argument" $\endgroup$ – kglr Jul 3 at 5:17
  • $\begingroup$ +1, now I see that, and then the example -(-2,3,4) makes sense now. I suck at reading&&math! Thank you :) $\endgroup$ – CA Trevillian Jul 3 at 5:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.