I often want to write functions that take as an argument either a) a rule or b) a list of rules. As an example, when using Replace with just one rule, it does not matter whether you give it as a list or not:
Replace[Range[10], 7->"seven", {1}]
Replace[Range[10], {7->"seven"}, {1}]
will both work as expected.
Now, if I wanted to set this up, I would use the listed form throughout the function body, and add a second function pattern to actually rewrite the non-listed Rule into a List:
Replace[expr_, rules_Rule, levelspec_] := Replace[expr, {rules}, levelspec]
Replace[expr_, rules_List, levelspec_] := the function body...
Is there a way to write a pattern which matches both forms and returns the listed one?
It is, of course, not too hard to write the function body in a way that it supports both forms. But actually I would like to have it done in the pattern already, so I will not have to take special care of it and can easily extend existing functions to support this feature.
_Rule | {__Rule}but this will shift handling the list-vs-nonlist problem elsewhere, so it doesn't simplify things. I prefer the solution you describe, i.e.f[r_Rule] := f[{r}]. – Szabolcs Jun 20 '14 at 14:53attern::patv: Name x used for both fixed and variable length patterns.as an error. – Theo Tiger Jun 20 '14 at 14:58r: (_Rule | {__Rule})then in the body of your function check ifris a list of rules or a single rule. This is a single pattern, but it makes things more complicated. This is why I think that your solution is the best alternative. – Szabolcs Jun 20 '14 at 15:00Range@10 /. {7 -> "seven", 8 -> "eight"}andRange@10 /. {{7 -> "seven", 8 -> "eight"}}andRange@10 /. {{{7 -> "seven", 8 -> "eight"}}}for example. – mfvonh Jun 20 '14 at 16:00patvmessage is not an error. It is simply a warning. The definition is still made as requested and you can choose to ignore the message if you wish. – Oleksandr R. Jun 21 '14 at 12:38{rules}throughout the function body. Any way to have the rules always listed (so thatrulesalways is a list, no matter whether it was given as_Ruleor as{__Rules})? – Theo Tiger Jun 21 '14 at 14:38f[r_Rule | {r__Rule}] := {r}. – Szabolcs Jun 22 '14 at 03:01