Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

One more question for today: I'm trying to show two random integers with a plus (+) sign between them, in an unevaluated form. I know how Hold and HoldForm work, but they hold everything, including the RandomInteger:

Hold[RandomInteger[100] + RandomInteger[100]]

I've tried then Evaluate before RandomInteger, but that doesn't seem to do the trick.

Any help with this? Very much appreciated, as always!

share|improve this question
4  
This is a straight-forward case for the Trott-Strzebonski technique, discussed e.g. here. Apply this rule to your expression: r_RandomInteger :> With[{eval = r}, eval /; True]. The reason Evaluate does not help is that it is too deep for it. –  Leonid Shifrin Sep 5 '13 at 17:41

4 Answers 4

up vote 7 down vote accepted
HoldForm[#1 + #2]&[RandomInteger[100], RandomInteger[100]]
 (* 77 + 84 *)
share|improve this answer
    
+1 but see my answer too for my personal variation –  Mr.Wizard Sep 6 '13 at 17:21

I propose:

HoldForm[+##] & @@ RandomInteger[100, 2]
share|improve this answer
    
The form +## rates highly on my weirdo meter. Weirdo. BTW, +1. :) –  rcollyer Sep 6 '13 at 17:16
    
@rcollyer Yes, it's a favorite of mine, thank-you-very-much. :D –  Mr.Wizard Sep 6 '13 at 17:21
    
Great! Your solution is very compact and can be generalized to any numbers of terms, +1 :) –  ybeltukov Sep 6 '13 at 17:33
    
@ybeltukov I'm glad you appreciate it. Thanks for the vote. –  Mr.Wizard Sep 6 '13 at 17:37
1  
@Blackbird It is not directly documented that I know of, but it comes from an understanding of Mathematica's parsing. +x parses as Plus[x] as can be seen with Hold[+x] // FullForm. So +## is Plus[##] and then it's just a matter of SlotSequence which is directly documented. As a second example 1 x parses as Times[1, x] so we can use 1 ## as shorthand for multiplying arguments. –  Mr.Wizard Sep 6 '13 at 18:22

This way you can hold it too,

Hold[Plus[a, b]] /. {a -> RandomInteger[100], b -> RandomInteger[100]}

Hold[91 + 4]

HoldForm[Plus[a, b]] /. {a -> RandomInteger[100], 
  b -> RandomInteger[100]}

87+22

Read the difference between Hold and HoldForm to know they are very close.

share|improve this answer
1  
This is a nice place to show the difference between Rule and RuleDelayed. –  rcollyer Sep 6 '13 at 17:15

Late to this party, but here's a nice trick that surprisingly works:

Composition[HoldForm, Plus] @@ RandomInteger[100, 2]

OR

Composition[HoldForm, Plus] @@ {RandomInteger[100], RandomInteger[100]}
share|improve this answer

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.