8
$\begingroup$

I am trying to extract an expression of given pattern from the list of the form

list = {a -> b, c -> d} (* typical output of Solve *)

For example, all the expressions which look like x -> 0.

For obvious reasons, Cases[list, _ -> 0] does not work. What should I do instead?

$\endgroup$
4
  • 1
    $\begingroup$ I'd say 90% methods there make it a good duplicate? Do you agree? 65892, another related: 3916 $\endgroup$
    – Kuba
    Jul 3 '17 at 6:11
  • 1
    $\begingroup$ This is literally the only example listed under "Possible issues" for Cases. Close as "easily found in the documentation". $\endgroup$
    – LLlAMnYP
    Jul 3 '17 at 6:34
  • $\begingroup$ @LLlAMnYP I agree that this is easily found in the documentation for Cases but I think this question is more useful to the community marked as a duplicate than simply closed, so I did that. I do not mean any disrespect to you by this action. If you feel that my action was inappropriate please tell me. $\endgroup$
    – Mr.Wizard
    Jul 4 '17 at 5:00
  • $\begingroup$ @Mr.Wizard yes, duplication is an important mechanism, if only for the fact that so many don't bother reading the documentation. On a meta-note, I got a feeling that this QA is rep-farming: trivial Q, immediate textbook A... I'd make a meta post, but applying Hanlon's razor is easier. $\endgroup$
    – LLlAMnYP
    Jul 4 '17 at 6:58
8
$\begingroup$

HoldPattern[] solves the problem!

Cases[list, HoldPattern[_ -> 0]]

$\endgroup$
3
  • 4
    $\begingroup$ You can also use Pattern: Cases[{a -> 0, b -> 1}, s : (_ -> 0)]. -- And Verbatim[Rule][_, 0], etc. $\endgroup$
    – Michael E2
    Jul 3 '17 at 5:12
  • 1
    $\begingroup$ I think the answer should be Verbatim[Rule][_,0] as that is the construct especially made for such cases. The others are just working for this particular case "by accident" but are meant for different use cases... $\endgroup$ Jul 3 '17 at 8:54
  • 3
    $\begingroup$ "The others are just working for this particular case "by accident" but are meant for different use cases". How do you conclude that? The documentation for HoldPattern specifically mentions the use case Cases[{a -> b, c -> d}, HoldPattern[a -> _]]. $\endgroup$ Jul 3 '17 at 9:49

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