-1
$\begingroup$

Let's take a composite Mathematica command:

A[B[]]

where A and B - two arbitrary Mathematica commands and [] - inner object of arbitrary structure

What code to use to swap them, i.e.:

A[B[]]$\xrightarrow{\text{?}}$B[A[]]

for example:

D[Sin[]]$\xrightarrow{\text{?}}$Sin[D[]]

Let's also consider a more complicated case:

for expression D[Transpose[x] + Sin[x y], x]

we must get Transpose[D[x, x]] + Sin[D[x y, x]]

$\endgroup$
1
  • $\begingroup$ This seems a bit like an XY problem. Can you please elaborate more on what you are actually trying to achieve? $\endgroup$
    – Domen
    Commented Nov 2, 2022 at 17:33

1 Answer 1

2
$\begingroup$

D is the derivative operator in MMA. Therefore, I am using DD.

You may achieve your goal using "ReplaceAll" with the following pattern:

pat= x1_[x2_[x3_]] -> x2[x1[x3]]

With this, e.g.:

DD[Sin[a]] /. pat
(* Sin[DD[a]] *)
$\endgroup$
7
  • $\begingroup$ As far as I understand, to work with the D command, I need to use Unprotect and Protect? It all boils down to working with the rules one way or another... It would be interesting to try some alternatives. Is it possible to avoid the removal of protection from the D command? $\endgroup$
    – ayr
    Commented Nov 2, 2022 at 15:53
  • $\begingroup$ @dtn, are you really saying that you want to override D, or are you saying that D just happens to be one of the heads you want to swap with? If the latter, then it gets more complicated, because D expects more than one argument. $\endgroup$
    – lericr
    Commented Nov 2, 2022 at 15:59
  • 1
    $\begingroup$ @lericr "D expects more than one argument." Actually D[a] returns a, this is a surprisng hidden syntax :) . You may want to read this: mathematica.stackexchange.com/a/163273/1871 $\endgroup$
    – xzczd
    Commented Nov 2, 2022 at 16:05
  • $\begingroup$ @lericr I just realized that it's much more complicated than that. So we are talking about a more complex version. Let's say ... there is such an expression D[Transpose[x] + Sin[x y], x], and the desired result should look like Transpose[D[x, x]] + Sin[D[x y, x]] $\endgroup$
    – ayr
    Commented Nov 2, 2022 at 16:18
  • $\begingroup$ @xzczd, yeah, I assumed that form wasn't meaningful, or was used "accidentally" in the example. $\endgroup$
    – lericr
    Commented Nov 2, 2022 at 16:40

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