Injecting a sequence of expressions into a held expression
{3, 4} /. {x__} :> Hold[{1, 2, x}]
Hold[{1, 2, 3, 4}]
Leonid Shifrin used this here long before I wrote this answer.
In light of Leonid's comment to halirutan it is worth pointing out that you can inject expressions from an arbitrary head including Hold. You can also use ->
rather than :>
like this:
expr = Hold[{1, 2, x}];
Hold[6/2, 2 + 2] /. _[x__] -> expr
Hold[{1, 2, 6/2, 2 + 2}]
How about this:
ClearAll[inject];
SetAttributes[inject, HoldRest];
inject[Hold[{args__}], new__] := Hold[{args, new}]
This will also accept Sequence[3,4]
as a second argument. Sequences are spliced, while arguments themselves not evaluated.
EDIT
You can also use a composite rule, with some head s
instead of Sequence
(you can localize s
if needed):
Hold[{1, 2, x}] /. x -> s[3, 4] /.
f_[left___, s[middle___], right___] :> f[left, middle, right]
One way is to use Function
and the possibility of SlotSequence
. I define an additional function f
to be sure nothing gets evaluated:
f[x_] := Print["Evaluated"];
Function[Hold[Do[f[1], ##]]][{i, 5}, {j, 5}]
(*
Hold[Do[f[1], {i, 5}, {j, 5}]]
*)