## Visually identifying differences between two Mathematica functions

5

4

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.

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], ")"}]


2/ or using showStringDiff

SystemDumpshowStringDiff[ToString@Definition[f],ToString@Definition[g]]


3/ Finally This other code by LeonidShifrin

  visualExprDiff[str1, str2]


yields

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).

1

Have you seen this Q/A?

– Leonid Shifrin – 2020-03-19T13:48:59.353

1It 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. – Leonid Shifrin – 2020-03-19T15:29:24.153

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. – Leonid Shifrin – 2020-03-19T16:34:57.587