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]]


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

  • 2
    $\begingroup$ Riffle[list, x] /. x :> RandomInteger[1] $\endgroup$ – garej Mar 30 '16 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.

| improve this answer | |
  • $\begingroup$ I don't know how to express my exciting when the first glance for your answer..You touch my G-point. $\endgroup$ – yode Mar 30 '16 at 18:13
  • $\begingroup$ @yode I'm glad you find it useful. Thanks for the accept! $\endgroup$ – user31159 Mar 31 '16 at 12:12

Riffle does not have the HoldAll or HoldRest attribute:



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]
| improve this answer | |
  • 2
    $\begingroup$ Good explaination.Thanks a lot. $\endgroup$ – yode Mar 30 '16 at 6:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.