Map patterns to values

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

David Baghdasaryan

Posted 2020-03-12T17:01:36.680

Reputation: 745

Can you give a specific example? This is my input, this is my desired output. I do not understand what it means to apply a pattern to a list. – Szabolcs – 2020-03-12T17:12:57.017

Sure, This is my input foo /@ listofPatterns and this what I except {1, 1.5, "foo"} the question is to define foo correctly. – David Baghdasaryan – 2020-03-12T17:15:55.240

Related, possible duplicates: (2778), (17892), (43923)

– Mr.Wizard – 2020-03-12T21:45:06.557

Answers

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.

Posted 2020-03-12T17:01:36.680

Reputation: 58 546