3
$\begingroup$

I want to print, for example Print[a + b], but first

a = RandomChoice[{-3, -2, -1, 1, 2, 3}];
b = RandomChoice[{-3, -2, -1, 1, 2, 3}];

And every time you calculate the random value, I can see
2 + 3 or -3 + 1 without evaluating.

$\endgroup$
  • $\begingroup$ If you have a longer list of numbers, say {a1, a2, ..., an}, then you could do StringRiffle[ToString /@ {a1, a2, ..., an}, "+"]. One possible problem is that you'll get things like 2 + -3 if you don't select + or - based on the sign. $\endgroup$ – aardvark2012 Dec 20 '17 at 3:28
4
$\begingroup$

It is hard to explain the details without explaining the whole Mathematica evaluation chain. There are many ways to achieve this. If you just want to "see" the sum, then you can start by evaluating the line

Dynamic[a] + Dynamic[b]

after that, you can evaluate as often as you want

a = RandomChoice[{-3, -2, -1, 1, 2, 3}];
b = RandomChoice[{-3, -2, -1, 1, 2, 3}];

and see the update. Note that you want to use Defer if you try something like

Defer[Dynamic[a] + Dynamic[a]]

If you really want to print it, then Nassers advice works as well. Or you can use Inactivate

a = RandomChoice[{-3, -2, -1, 1, 2, 3}];
b = RandomChoice[{-3, -2, -1, 1, 2, 3}];
Inactivate[a + b]
$\endgroup$
3
$\begingroup$

You can use Inactive, HoldForm, Defer ...

{a, b} = RandomChoice[{-3, -2, -1, 1, 2, 3}, 2]; 
Defer[#+#2]&[a,b]
HoldForm[#+#2]&[a,b]
Inactive[Plus][a,b]
With[{a = a, b = b}, HoldForm[a + b]]
With[{a = a, b = b}, Defer[a + b]]

all give

-2 + 3

$\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.