Skip to main content

pattern matching - Cases with Alternatives failed


Consider this list of rules


rules = {a -> 1, b -> 2, c -> 3}


I'd like to fish some of the rules out of such a list using Cases. All is well if I hard code the Alternatives to fish out:


Cases[rules, HoldPattern[a|b -> _]]


{a -> 1, b -> 2}



But, if I try to dynamically generate the Alternatives from data, it fails:


targets = {a, b}
Cases[rules, HoldPattern[Alternatives @@ targets -> _]]



{}



I've tried the following shots-in-the-dark


Cases[rules, HoldPattern[Evaluate[Alternatives @@ targets] -> _]]


{}



Cases[rules, HoldPattern[ReleaseHold[Alternatives @@ targets] -> _]]



{}



MMA 10.0.2.0 on Mac Mavericks.



Answer



HoldPattern has attribute HoldAll


Attributes[HoldPattern]
(* {HoldAll, Protected} *)


So one can use the following injection


Cases[rules, HoldPattern[Alternatives@## -> _] & @@ targets]
(* {a -> 1, b -> 2} *)

P.S. Conceptually, HoldPattern is here the wrong tool for the job, even if this works. See Leonid's answer.


Comments