Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
2  
Riffle[list, x] /. x :> RandomInteger[1] – garej Mar 30 at 6:29
up vote 4 down vote accepted

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.

share|improve this answer
    
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]
share|improve this answer
2  
Good explaination.Thanks a lot. – yode Mar 30 at 6:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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