How to replace all elements of a list by a rule "element" -> "element_"
Here is one way:
Pattern[#, Blank[]] & /@ {a, b, c, d, e, f, g, h, i, j}
(* {a_, b_, c_, d_, e_, f_, g_, h_, i_, j_} *)
An inspection of the FullForm
of a_
reveals why this works:
a_ // FullForm
(* Pattern[a, Blank[]] *)
We can abbreviate slightly if we realize that the InputForm
of Blank[]
is _
:
Pattern[#, _] & /@ {a, b, c, d, e, f, g, h, i, j}
(* {a_, b_, c_, d_, e_, f_, g_, h_, i_, j_} *)
As an alternative approach, one might think to use pattern-matching replacement instead:
Replace[{a, b, c, d, e, f, g, h, i, j}, s_Symbol :> s_, {1}]
(*
RuleDelayed::rhs: Pattern s_ appears on the right-hand side of rule s_Symbol:>s_.
{a_, b_, c_, d_, e_, f_, g_, h_, i_, j_}
*)
... but Mathematica issues a warning because most of the time having a pattern on the right-hand side of a rule is a mistake. In this particular case it is not an error, so we have to use Quiet
to tell Mathematica that:
Quiet[Replace[{a, b, c, d, e, f, g, h, i, j}, s_Symbol :> s_, {1}], RuleDelayed::rhs]
(* {a_, b_, c_, d_, e_, f_, g_, h_, i_, j_} *)
A few additional alternatives to inject patterns on the rhs:
list = {a, b, c, d, e, f, g, h, i, j};
Replace[list, a_ :> (x_ /. x -> a), 1]
{a_, b_, c_, d_, e_, f_, g_, h_, i_, j_}
Replace[list, a_ :> (Pattern[#, _] &@a), 1]
{a_, b_, c_, d_, e_, f_, g_, h_, i_, j_}
Activate @ Replace[list, a_ :> Inactive[Pattern][a, _], 1]
{a_, b_, c_, d_, e_, f_, g_, h_, i_, j_}
Replace[list, a_ :> foo[a, _], 1] /. foo -> Pattern
{a_, b_, c_, d_, e_, f_, g_, h_, i_, j_}
convert it to string and then deal with it
ToExpression@StringJoin[#,"_"]&/@ToString/@{a,b,c,d,e}
a shorter way
ToExpression@StringJoin[ToString@#,"_"]&/@{a,b,c,d,e}