Exponentiation order: Difference between revisions

Add Red
(Added solution for Action!)
(Add Red)
Line 879:
 
The Unicode exponent form without parentheses ends up raising to the 32nd power. Nor are you even allowed to parenthesize it the other way: <tt>5(³²)</tt> would be a syntax error. Despite all that, for programs that do a lot of squaring or cubing, the postfix forms can enhance both readability and concision.
 
=={{header|Red}}==
In Red, operators simply evaluate left to right. As this differs from mathematical order of operations, Red provides the <code>math</code> function which evaluates a block using math rules instead of Red's default evaluation. One could also use the <code>power</code> function, sidestepping the issue of evaluation order entirely. All three approaches are shown.
<lang rebol>Red["Exponentiation order"]
 
exprs: [
[5 ** 3 ** 2]
[(5 ** 3) ** 2]
[5 ** (3 ** 2)]
[power power 5 3 2] ;-- functions too
[power 5 power 3 2]
]
 
foreach expr exprs [
print [mold/only expr "=" do expr]
if find expr '** [
print [mold/only expr "=" math expr "using math"]
]
]</lang>
{{out}}
<pre>
5 ** 3 ** 2 = 15625
5 ** 3 ** 2 = 1953125 using math
(5 ** 3) ** 2 = 15625
(5 ** 3) ** 2 = 15625 using math
5 ** (3 ** 2) = 1953125
5 ** (3 ** 2) = 1953125 using math
power power 5 3 2 = 15625
power 5 power 3 2 = 1953125
</pre>
 
=={{header|REXX}}==
1,808

edits