8
$\begingroup$

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!

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

I propose:

HoldForm[+##] & @@ RandomInteger[100, 2]
$\endgroup$
  • $\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
3
$\begingroup$

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.

$\endgroup$
  • 1
    $\begingroup$ This is a nice place to show the difference between Rule and RuleDelayed. $\endgroup$ – rcollyer Sep 6 '13 at 17:15
2
$\begingroup$

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]}
$\endgroup$

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.