| 1 | import math |
| 2 | |
| 3 | struct Exponent { |
| 4 | value int |
| 5 | } |
| 6 | |
| 7 | fn (a Exponent) **(b Exponent) Exponent { |
| 8 | mut result := 1 |
| 9 | for _ in 0 .. b.value { |
| 10 | result *= a.value |
| 11 | } |
| 12 | return Exponent{ |
| 13 | value: result |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | const const_power = 2 ** 5 |
| 18 | |
| 19 | fn test_power_operator_with_ints() { |
| 20 | assert const_power == 32 |
| 21 | assert 2 ** 3 == 8 |
| 22 | assert 2 ** 3 ** 2 == 512 |
| 23 | assert -2 ** 2 == -4 |
| 24 | assert (-2) ** 2 == 4 |
| 25 | } |
| 26 | |
| 27 | fn test_power_assign_with_ints() { |
| 28 | mut value := 3 |
| 29 | value **= 3 |
| 30 | assert value == 27 |
| 31 | } |
| 32 | |
| 33 | fn test_power_operator_with_floats() { |
| 34 | assert math.abs(9.0 ** 0.5 - 3.0) < 1e-9 |
| 35 | } |
| 36 | |
| 37 | fn test_power_operator_overload() { |
| 38 | mut value := Exponent{ |
| 39 | value: 2 |
| 40 | } |
| 41 | assert (value ** Exponent{ |
| 42 | value: 3 |
| 43 | }).value == 8 |
| 44 | value **= Exponent{ |
| 45 | value: 3 |
| 46 | } |
| 47 | assert value.value == 8 |
| 48 | } |
| 49 | |