5
$\begingroup$

Context

Let us assume we have two functions defined in Mathematica. I am interested in spotting the differences in the code for the two functions.

Example

  f[x_,y_]:= Module[{t}, t= x+y; Sin[t]];
  g[x_,y_]:= Module[{t}, t= x-y; Sin[t]];

I would like to be able to select both codes and have the front end produce a highlight of the differences in colour.

Mathematica graphics

This is something that word editors do routinely.

Attempt

I don't know anything about front-end coding. This 3 solutions might be a good starting point (inline not with the FE)?

1/ Following this post

st1 = Definition[f] // ToString
st2 = Definition[g] // ToString
sa = SequenceAlignment[st1, st2];
 Row@
 Flatten[sa /. {a_, b_} :> {Style[a, Red], "(", Style[b, Green], ")"}]

Mathematica graphics

2/ or using showStringDiff

System`Dump`showStringDiff[ToString@Definition[f],ToString@Definition[g]]

Mathematica graphics

3/ Finally This other code by LeonidShifrin

  visualExprDiff[str1, str2]   

yields

Mathematica graphics

If one assigns

str1 = "Hold[" <> ToString[Definition[f]] <> "]" // ToExpression
str2 = "Hold[" <> ToString[Definition[g]] <> "]" // ToExpression

Update

FIY the showStringDiff above (though not interactive) did the job for me and produced the difference I needed to spot my bug.

PS: One thing this would require is selecting two functions which might not be next to each other in the notebook (though this can be avoided by duplicating the code I guess).

$\endgroup$
3
  • 1
    $\begingroup$ Have you seen this Q/A? $\endgroup$ Mar 19, 2020 at 13:48
  • 1
    $\begingroup$ It should be doable, but not a one-liner. You would have to compare DownValues, OwnValues, possibly also SubValues and UpValues. Further, each function can have multiple definitions / rules defined for it, and they may have somewhat different ordering for the two functions. So one would have to somehow first preprocess the definitions and extract which pieces to compare to which, if one wants to get a better / more meaningful comparison. This isn't impossible, but would take some work to implement. $\endgroup$ Mar 19, 2020 at 15:29
  • $\begingroup$ Yeah, you could use that code, I guess, although there surely exists a way to avoid ToString - ToExpression stage. As to the answers, I have no strong opinion, but I'd probably leave things as they are now, at least for some time. $\endgroup$ Mar 19, 2020 at 16:34

0

Your Answer

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

Browse other questions tagged or ask your own question.