Skip to main content
Post Closed as "Duplicate" by Mr.Wizard
edited title
Link
Szabolcs
  • 238.9k
  • 32
  • 653
  • 1.3k

Function pattenpattern to support listed and non-listed arguments

Source Link
Theo Tiger
  • 1.3k
  • 8
  • 11

Function patten to support listed and non-listed arguments

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.