Skip to content

Instantly share code, notes, and snippets.

@lshifr
Created February 9, 2014 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lshifr/8900880 to your computer and use it in GitHub Desktop.
Save lshifr/8900880 to your computer and use it in GitHub Desktop.
ClearAll[csub];
csub[expr_Hold, rules_List, limitCount_] :=
With[{newrule =
Replace[If[# =!= {} && #[[-1, -1]] > 1, #[[-1, 1]], {}] &@
SortBy[Tally[
Cases[expr,
x_ /; Depth[Unevaluated[x]] > 2 &&
LeafCount[Unevaluated[x]] > limitCount :> Hold[x],
Infinity]], Last],
Hold[x_] :> (HoldPattern[x] -> Unique[])]},
csub[expr /. newrule, Append[rules, newrule], limitCount] /;
newrule =!= {}];
csub[Hold[expr_], rules_, _] :=
Append[
Replace[
Thread[(rules /. (Verbatim[HoldPattern][x_] -> var_) :>
Hold[var :> x]), Hold], {} -> Hold[]
],
Unevaluated[expr]
] /. Hold[defs_, exp_] :> {Hold[defs], Hold[exp]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment