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
  • 2
    $\begingroup$ check -b // FullForm $\endgroup$
    – kglr
    Commented Jul 1, 2019 at 13:27
  • 1
    $\begingroup$ @kglr ugh...${}{}$ $\endgroup$ Commented Jul 1, 2019 at 13:30

1 Answer 1

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$
3
  • $\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$ Commented Jul 3, 2019 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
    Commented Jul 3, 2019 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$ Commented Jul 3, 2019 at 5:23

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