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!

  • 5
    $\begingroup$ 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. $\endgroup$ – Leonid Shifrin Sep 5 '13 at 17:41
HoldForm[#1 + #2]&[RandomInteger[100], RandomInteger[100]]
 (* 77 + 84 *)
  • $\begingroup$ +1 but see my answer too for my personal variation $\endgroup$ – Mr.Wizard Sep 6 '13 at 17:21

I propose:

HoldForm[+##] & @@ RandomInteger[100, 2]
  • $\begingroup$ The form +## rates highly on my weirdo meter. Weirdo. BTW, +1. :) $\endgroup$ – rcollyer Sep 6 '13 at 17:16
  • 1
    $\begingroup$ @rcollyer Yes, it's a favorite of mine, thank-you-very-much. :D $\endgroup$ – Mr.Wizard Sep 6 '13 at 17:21
  • $\begingroup$ Great! Your solution is very compact and can be generalized to any numbers of terms, +1 :) $\endgroup$ – ybeltukov Sep 6 '13 at 17:33
  • $\begingroup$ @ybeltukov I'm glad you appreciate it. Thanks for the vote. $\endgroup$ – Mr.Wizard Sep 6 '13 at 17:37
  • 2
    $\begingroup$ @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. $\endgroup$ – 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]}


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

  • 1
    $\begingroup$ This is a nice place to show the difference between Rule and RuleDelayed. $\endgroup$ – 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]


Composition[HoldForm, Plus] @@ {RandomInteger[100], RandomInteger[100]}

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.