3

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} *)
dionys
  • 4,321
  • 1
  • 19
  • 46

1 Answers1

3

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"}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371