Exponentiation with infix operators in (or operating on) the base: Difference between revisions

Content deleted Content added
m added a couple of related tasks.
PureFox (talk | contribs)
Added Wren
Line 157: Line 157:
5 3 ║ -x**p -125 ║ -(x)**p -125 ║ (-x)**p -125 ║ -(x**p) -125
5 3 ║ -x**p -125 ║ -(x)**p -125 ║ (-x)**p -125 ║ -(x**p) -125
───── ──────╨─────────── ───────╨─────────── ───────╨─────────── ───────╨─────────── ──────
───── ──────╨─────────── ───────╨─────────── ───────╨─────────── ───────╨─────────── ──────
</pre>

=={{header|Wren}}==
{{libheader|Wren-fmt}}
Wren uses the pow() method for exponentiation of numbers and, whilst it supports operator overloading, there is no way of adding a suitable infix operator to the existing Num class.

Also inheriting from the Num class is not recommended and will probably be banned altogether from the next version.

However, what we can do is to wrap Num objects in a new Num2 class and then add exponentiation and unary minus operators to that.

Ideally what we'd like to do is to use a new operator such as '**' for exponentiation (because '^' is the bitwise exclusive or operator) but we can only overload existing operators with their existing precedence and so, for the purposes of this task, '^' is the only realistic choice.
<lang ecmascript>import "/fmt" for Fmt

class Num2 {
construct new(n) { _n = n }

n { _n}

^(exp) {
if (exp is Num2) exp = exp.n
return Num2.new(_n.pow(exp))
}

- { Num2.new(-_n) }

toString { _n.toString }
}

var ops = ["-x^p", "-(x)^p", "(-x)^p", "-(x^p)"]
for (x in [Num2.new(-5), Num2.new(5)]) {
for (p in [Num2.new(2), Num2.new(3)]) {
Fmt.write("x = $2s p = $s | ", x, p)
Fmt.write("$s = $4s | ", ops[0], -x^p)
Fmt.write("$s = $4s | ", ops[1], -(x)^p)
Fmt.write("$s = $4s | ", ops[2], (-x)^p)
Fmt.print("$s = $4s", ops[3], -(x^p))
}
}</lang>

{{out}}
<pre>
x = -5 p = 2 | -x^p = 25 | -(x)^p = 25 | (-x)^p = 25 | -(x^p) = -25
x = -5 p = 3 | -x^p = 125 | -(x)^p = 125 | (-x)^p = 125 | -(x^p) = 125
x = 5 p = 2 | -x^p = 25 | -(x)^p = 25 | (-x)^p = 25 | -(x^p) = -25
x = 5 p = 3 | -x^p = -125 | -(x)^p = -125 | (-x)^p = -125 | -(x^p) = -125
</pre>
</pre>