v2 / vlib / v / tests / power_operator_test.v
48 lines · 41 sloc · 739 bytes · 0f3332b1f3c761cd5215d968b3afef24cd3dc3cb
Raw
1import math
2
3struct Exponent {
4 value int
5}
6
7fn (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
17const const_power = 2 ** 5
18
19fn 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
27fn test_power_assign_with_ints() {
28 mut value := 3
29 value **= 3
30 assert value == 27
31}
32
33fn test_power_operator_with_floats() {
34 assert math.abs(9.0 ** 0.5 - 3.0) < 1e-9
35}
36
37fn 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