10
$\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$
1
  • 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$ Commented Sep 5, 2013 at 17:41

4 Answers 4

12
$\begingroup$
HoldForm[#1 + #2]&[RandomInteger[100], RandomInteger[100]] (* 77 + 84 *) 
$\endgroup$
1
  • $\begingroup$ +1 but see my answer too for my personal variation $\endgroup$ Commented Sep 6, 2013 at 17:21
11
$\begingroup$

I propose:

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.