# Why SetDelayed won't work

I'm trying to do this:

Riffle[list = {a, b, c, d, e, f}, tem = RandomInteger[1, Length@list-1]]


{a, 0, b, 0, c, 1, d, 0, e, 0, f}

But I think this method is too verbose. I don't want to count the length. So I want to do it like this:

Riffle[{a, b, c, d, e, f}, x := RandomInteger[1]]


And get this:

{a, Null, b, Null, c, Null, d, Null, e, Null, f}

Or we use RuleDelayed:

Riffle[{a, b, c, d, e, f}, x :> RandomInteger[1]]


{a,1:>RandomInteger[1],b,1:>RandomInteger[1],c,1:>RandomInteger[1],d,1:>RandomInteger[1],e,1:>RandomInteger[1],f}

What's wrong with my solution? How can I do this without counting the length?

-
Riffle[list, x] /. x :> RandomInteger[1] – garej Mar 30 at 6:29

The question has been answered by garej in his comment and by C. E., but in case you are interested in an alternative solution which does not involve RuleDelayed and is in the spirit of evaluation control, you could do

Riffle[{a, b, c, d, e, f}, Unevaluated@RandomInteger[1]]

(* {a, 0, b, 1, c, 0, d, 0, e, 1, f} *)


Unevaluated prevents temporarily the evaluation of RandomInteger[1], so that the list is riffled with RandomInteger[1] verbatim. The intermediate step of the above evaluation is therefore:

(* {a, RandomInteger[1], b, RandomInteger[1], c,
RandomInteger[1], d, RandomInteger[1], e, RandomInteger[1], f} *)


(as the Trace shows). Each RandomInteger will then evaluate.

-
I don't know how to express my exciting when the first glance for your answer..You touch my G-point. – yode Mar 30 at 18:13
@yode I'm glad you find it useful. Thanks for the accept! – Xavier Mar 31 at 12:12

Riffle does not have the HoldAll or HoldRest attribute:

Attributes[Riffle]


{Protected}

The documentation for SetDelayed says that

lhs:=rhs returns Null if the assignment specified can be performed, and returns \$Failed otherwise.

So what happens in your first example is that the second argument evaluates to Null before it is passed to Riffle.

Your second example is expected because RuleDelayed has the HoldRest attribute, which means that the second argument (RandomInteger[1]) is held. x evaluates to whatever value it has (1) because RuleDelayed does not have the HoldFirst or HoldAll attribute.

garej offers a good solution in his comment. Use an undefined symbol and ReplaceAll:

Riffle[list, x] /. x :> RandomInteger[1]

-
Good explaination.Thanks a lot. – yode Mar 30 at 6:37