Exponentiation with infix operators in (or operating on) the base: Difference between revisions
Content added Content deleted
(Added Go) |
|||
Line 119: | Line 119: | ||
5 2 -x**p 25 -(x)**p 25 (-x)**p 25 -(x**p) -25 |
5 2 -x**p 25 -(x)**p 25 (-x)**p 25 -(x**p) -25 |
||
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|Go}}== |
|||
Go uses the math.Pow function for exponentiation and doesn't support operator overloading at all. Consequently, it is not possible to conjure up an infix operator to do the same job. |
|||
Perhaps the closest we can get is to define a derived type (''float'' say) based on float64 and then give it a method with a short name (''p'' say) to provide exponentiation. |
|||
This looks odd but is perfectly workable as the following example shows. However, as a method call, ''x.p'' is always going to take precedence over the unary minus operator and will always require the exponent to be enclosed in parentheses. |
|||
Note that we can't call the method ''↑'' (or similar) because identifiers in Go must begin with a Unicode letter and using a non-ASCII symbol would be awkward to type on some keyboards in any case. |
|||
<lang go>package main |
|||
import ( |
|||
"fmt" |
|||
"math" |
|||
) |
|||
type float float64 |
|||
func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) } |
|||
func main() { |
|||
ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"} |
|||
for _, x := range []float{float(-5), float(5)} { |
|||
for _, e := range []float{float(2), float(3)} { |
|||
fmt.Printf("x = %2.0f e = %0.0f | ", x, e) |
|||
fmt.Printf("%s = %4.0f | ", ops[0], -x.p(e)) |
|||
fmt.Printf("%s = %4.0f | ", ops[1], -(x).p(e)) |
|||
fmt.Printf("%s = %4.0f | ", ops[2], (-x).p(e)) |
|||
fmt.Printf("%s = %4.0f\n", ops[3], -(x.p(e))) |
|||
} |
|||
} |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
x = -5 e = 2 | -x.p(e) = -25 | -(x).p(e) = -25 | (-x).p(e) = 25 | -(x.p(e)) = -25 |
|||
x = -5 e = 3 | -x.p(e) = 125 | -(x).p(e) = 125 | (-x).p(e) = 125 | -(x.p(e)) = 125 |
|||
x = 5 e = 2 | -x.p(e) = -25 | -(x).p(e) = -25 | (-x).p(e) = 25 | -(x.p(e)) = -25 |
|||
x = 5 e = 3 | -x.p(e) = -125 | -(x).p(e) = -125 | (-x).p(e) = -125 | -(x.p(e)) = -125 |
|||
</pre> |
</pre> |
||
Line 136: | Line 176: | ||
x is 5, p is 3, -x^p is-125, -(x)^p is -125, (-x)^p is -125, -(x^p) is -125 |
x is 5, p is 3, -x^p is-125, -(x)^p is -125, (-x)^p is -125, -(x^p) is -125 |
||
</pre> |
</pre> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |