1
$\begingroup$

I have a function of the form f[a___][b___] which I would like to apply rules to, for example:

f[a___][b__] /; ! OrderedQ[{a}] && !OrderedQ[{b}] := Signature[{a}] Signature[{b}] f[Sequence @@Sort[{a}]][Sequence @@Sort[{b}]];
f[a__] /; ! OrderedQ[{a}] := Signature[{a}] f[Sequence @@ Sort[{a}]];

However, these two rules appear to conflict with each other since the second overrides the first, for example:

f[b, a][d, c]
f[b, a]

gives

(-f[a, b])[d, c]
-f[a, b]

The second one here is right, but the first is wrong. If I delete the second rule, I do get the desired output for the first (f[a,b][c,d]). Any idea how I can fix this?

$\endgroup$
2
  • 1
    $\begingroup$ I do not see how the first rule matches. Although " ! OrderedQ[{a}]" matches, but "OrderedQ[{b}]" does not match. $\endgroup$ Mar 28, 2023 at 11:19
  • $\begingroup$ Right you are @daniel-huber, I missed a ! on the OrderedQ[{b}]. Fixed now! $\endgroup$
    – Akoben
    Mar 28, 2023 at 11:23

1 Answer 1

4
$\begingroup$

The problem is that the 2nd definition will ALWAYS go first because WL always evaluates the head of an expression first. Either you stick with just the first definition or you need to do something like:

ClearAll[f]
f[a__] /; ! OrderedQ[{a}] := With[{
    sig = Signature[{a}],
    sort = Sort[{a}]
    },
   sig *f[Sequence @@ sort][##] &
 ];
f[a___][b__] /; ! OrderedQ[{b}] := Signature[{b}] f[a][Sequence @@ Sort[{b}]];

Another complication is, of course, that in WL you can't just have -f denote the function -f[#]&. There's not much you can do about that.

Edit

If I have to give a suggestion for this problem, I'd say that you need to change the way you call f:

ClearAll[f];
f[lists__List] /; ! AllTrue[{lists}, OrderedQ] := Times[
  Times @@ Map[Signature, {lists}],
  f @@ Map[Sort, {lists}]
]
f[{b, a}, {d, c}]
f[{b, a}]
f[{b, a}, {d, c}] f[{b, a}]

f[{a, b}, {c, d}]

-f[{a, b}]

-f[{a, b}] f[{a, b}, {c, d}]

$\endgroup$
4
  • $\begingroup$ Thanks for the answer, but it doesn't appear to work... Pasting your code with f[b, a][d, c] f[b, a] produces f[a, b][c, d] -f[Sequence @@ {a, b}][##1] & Any ideas? $\endgroup$
    – Akoben
    Mar 28, 2023 at 11:38
  • $\begingroup$ @Akoben That's because you cannot have it both ways. You cannot have f[b,a] evaluate to -f[a, b] AND have it still be an operator after that. $\endgroup$ Mar 28, 2023 at 13:44
  • $\begingroup$ Ahh, that is mighty annoying. Thanks anyway! $\endgroup$
    – Akoben
    Mar 28, 2023 at 14:53
  • 1
    $\begingroup$ @Akoben I added a suggestion for a different way to do it. $\endgroup$ Mar 28, 2023 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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