views:

62

answers:

1

In principle, what I want to use the following to generate a named pattern for later use:

In[1]:= Replace[var["x"],var[name_]:>Pattern[Apply[Symbol,name],_]]

I expected to see this result. A named pattern which I can use in subsequent rules:

Out[1]= x_

But instead, I got:

Out[1]= Pattern[Symbol @@ x,_]

The documentation says that Pattern[..] can only be used with a symbol as the first argument. Apply[Symbol, name] is not evaluated to return a symbol, so the Pattern[..] does not match.

Ho do I get a named pattern from some string name?

+3  A: 

The pattern name_ matches the string "x" which results in Apply[Symbol,"x"] which returns an object with head String. This is then passed to Pattern which returns what you see. To get what you expect you have to pass a Symbol to Pattern. Examine the various outputs you get with FullForm[].

You can probably do this by changing the fragment:

Pattern[Apply[Symbol,name],_]]

to

Pattern[Evaluate[ToExpression[name],_]]

but this will only work if ToExpression[name] returns a Symbol. I found that I had to force evaluation.

High Performance Mark
Thanks a bunch. That produced exactely what I wanted. :)
punytroll