1

Suppose I have a list of named patterns:

listofPatterns = {a_Integer, b_Real, c_?StringQ}

I would like to have a mapping from a pattern to a certain value like:

foo[HoldPattern[a_Integer]] = 1;

foo[HoldPattern[b_Real]] = 1.5;

foo[HoldPattern[c_?StringQ]] = "foo"; 

In order to apply that on my list

foo /@ listofPatterns

And I expect to have {1, 1.5, "foo"} as a result. What is the best way to achieve that?

Thank you, Davit

1 Answers1

3

When you need a pattern to match what is normally used as a pattern, you should use Verbatim:

foo[Verbatim[Pattern][_, Verbatim[Blank[Integer]]]] := 1

foo[Verbatim[Pattern][_, Verbatim[Blank[Real]]]] := 1.5

foo[Verbatim[PatternTest][_, StringQ]] := "foo"

foo /@ {a_Integer, b_Real, c_?StringQ}
(* {1, 1.5, "foo"} *)

When writing patterns like this, it's helpful to look at the full form of the patterns you want to match:

Column[FullForm /@ {a_Integer, b_Real, c_?StringQ}]
(* 
Pattern[a,Blank[Integer]]
Pattern[b,Blank[Real]]
PatternTest[Pattern[c,Blank[]],StringQ] 
*)
Jason B.
  • 68,381
  • 3
  • 139
  • 286