2
$\begingroup$

Replace and ReplaceAll apply rules only once, so multiple (redundant) rules can be given as input and the first instance of a rule is the only one that is applied.

How can I go about creating a function simplifyRules that can be given a list of rules and a relevant function (Replace, ReplaceAll, ReplaceRepeated, etc.) which returns a modified rules list without rules which are not applied by the function?

For example:

rules = FilterRules[{ImageSize->{Automatic, 300}, Scrollbars->{False, True}}~Join~Options[Pane], Options[Pane]];

simplifyRules[rules,ReplaceAll]
(* {ImageSize->{Automatic,300},
    Scrollbars->{False,True},
    Alignment->{Automatic,Automatic},
    Appearance->Automatic,
    AppearanceElements->Automatic,
    BaselinePosition->Automatic,
    BaseStyle->{},
    ContentPadding->True,
    DefaultBaseStyle->Pane,
    Enabled->Automatic,
    FrameMargins->Automatic,
    ImageMargins->0,
    ImageSizeAction->Automatic,
    ScrollPosition->{0,0},
    StripOnInput->False} *)
$\endgroup$
  • 2
    $\begingroup$ Merge[ First ] $\endgroup$ – Kuba Jan 12 '17 at 12:06
  • $\begingroup$ Related: (82626) $\endgroup$ – Mr.Wizard Jan 12 '17 at 14:24
3
$\begingroup$

Let's suppose you have:

rules = {1 -> "a", 1 -> "b", 1 -> "c", 4 -> "d", 2 -> "e", 3 -> "f"};

The only replace operation in which 1 -> "b", 1 -> "c", are used is ReplaceList:

ReplaceList[1, rules]
{"a", "b", "c"}

For other operations you can in recent versions Merge as Kuba commented, or use DeleteDuplicatesBy.

Merge[rules, First] // Normal

DeleteDuplicatesBy[rules, First]
{1 -> "a", 4 -> "d", 2 -> "e", 3 -> "f"}

{1 -> "a", 4 -> "d", 2 -> "e", 3 -> "f"}

(The output of Merge is an Association which in may places can be used like a Rule list, but I added Normal for fully compatible results.)

However for backward-compatibility and possibly better performance too I propose GatherBy:

GatherBy[rules, First][[All, 1]]
{1 -> "a", 4 -> "d", 2 -> "e", 3 -> "f"}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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