Message Boards Message Boards


Reverse engineering of complicated expressions

Posted 8 years ago
2 Replies
6 Total Likes
In Mathematica, everything is said to be an expression. As one becomes more proficient in this language, there is a natural tendency to construct expressions of ever-increasing size and complexity. Beyond that, in seeking to understand the Mathematica constructions of others, one can easily encounter expressions that are at first sight essentially incomprehensible.

It is the purpose of this posting to propose a very simple function, partslist, that the author has found valuable for gaining insight into the structure of seemingly bizarre expressions created by others, or even forgotten expressions created by oneself.

The definition is as follows:
cases[arg_, a_] := Cases[arg, a, {0, \}]
ngrid[arg_] := Grid[arg, Frame -> All, Alignment -> Left]
partslist[arg_] :=  ngrid@Reverse@Sort@(Reverse /@ Tally@(Head /@ cases[arg, _]))
The two links shown below give further details, along with an example involving an astronomy application of WolframAlpha.
2 Replies
I just noticed that the typography in my posting is screwed up.  It should be the following:
cases[arg_, a_] := Cases[arg, a, {0, \[Infinity]}];
ngrid[arg_] := Grid[arg, Frame -> All, Alignment -> Left];
partslist[arg_] :=
ngrid@Reverse@Sort@(Reverse /@ Tally@(Head /@ cases[arg, _]))
Sorry for the confusion.
It's a nice methodology to dissect expressions!

If you are interested in some more ways to analyse expressions (especially code), take a look at these discussions:
  •  These are some tools to read in-memory definitions easily and conveniently, primarily for a situation where you don't have the original source code.   I use these a lot.  It's convenient enough that I often reach for these tools even when I do have the source code (e.g. standard packages)
  •  This is for generating dependency graphs for packages, i.e. which function depends on which other ones in a package?  Suppose you are creating a CDF and you need to use some package function.  Since you can't load packages from a CDF, you need to extract the relevant function from the package and include it directly.  This tool will help figure out which parts of the package need to be included and which can be ignored.
  • This tool will readably format output from Trace.
  • This is a pretty printer for Mathematica code, written in Mathematica itself.
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract