4

When I Trace a rational number, I get this quite complicated output:

1/2 // Trace

{{1/2,1/2},1/2,1/2}

which under the hood looks like

{{HoldForm[1/2], HoldForm[1/2]}, HoldForm[1/2], HoldForm[1/2]}

At the same time, 1/2 is represented as Rational:

1/2 // FullForm

Rational[1, 2]

But if we do:

Rational[1, 2] // Trace

we get very simple output, which would be expected:

{Rational[1,2],1/2}

with underlying output being

{HoldForm[Rational[1, 2]], HoldForm[1/2]}

So, the question is: why MMA does so many steps when evaluating a rational number entered in a "pure" form and doesn't do it when Rational is used explicitly?

Stitch
  • 4,205
  • 1
  • 12
  • 28

1 Answers1

5

Using FullForm should help illuminate things:

Hold[1/2]//FullForm

Hold[Times[1,Power[2,-1]]]

We see that 1/2 is a bit more complicated than you might have expected. To evaluate this, you need to first evaluate Power[2, -1], and then you need to multiply that output with 1. So, let's see what happens in the Trace:

1/2//Trace
% /. h_HoldForm -> FullForm[h]

{{1/2,1/2},1/2,1/2}

{{HoldForm[Power[2,-1]],HoldForm[Rational[1,2]]},HoldForm[Times[1,Rational[1,2]]],HoldForm[Rational[1,2]]}

The Trace shows that the evaluation proceeded exactly as expected based on the FullForm of the input.

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
  • Thank you! That makes sense. What doesn't though, is why 1/2 needs to be presented in such a weird way. Any ideas why? – Stitch Jan 23 '17 at 17:54
  • Probably should make that a different question, a complete answer doesn't really work in a comment. The basic answer is to look at the cell expression corresponding to the input 1/2 (or more generally x/y) using Cell | ShowExpression, and think about how one would convert that cell to an expression. – Carl Woll Jan 23 '17 at 18:13
  • Thank you again. Will look into it and possibly post a question. – Stitch Jan 23 '17 at 18:18