| 1 | module main |
| 2 | |
| 3 | struct IntList { |
| 4 | mut: |
| 5 | values []int |
| 6 | } |
| 7 | |
| 8 | fn (l IntList) [] (index int) int { |
| 9 | return l.values[index] |
| 10 | } |
| 11 | |
| 12 | fn (mut l IntList) []= (index int, value int) { |
| 13 | l.values[index] = value |
| 14 | } |
| 15 | |
| 16 | struct Tensor { |
| 17 | mut: |
| 18 | last_set int |
| 19 | last_signature int |
| 20 | } |
| 21 | |
| 22 | fn (t Tensor) [] (parts []SliceIndex) int { |
| 23 | mut total := 0 |
| 24 | for part in parts { |
| 25 | if part.is_range { |
| 26 | total += 100 |
| 27 | if part.has_low { |
| 28 | total += part.low * 10 |
| 29 | } |
| 30 | if part.has_high { |
| 31 | total += part.high |
| 32 | } |
| 33 | } else { |
| 34 | total += part.value |
| 35 | } |
| 36 | } |
| 37 | return total |
| 38 | } |
| 39 | |
| 40 | fn (mut t Tensor) []= (parts []SliceIndex, value int) { |
| 41 | mut total := 0 |
| 42 | for part in parts { |
| 43 | if part.is_range { |
| 44 | total += 100 |
| 45 | if part.has_low { |
| 46 | total += part.low * 10 |
| 47 | } |
| 48 | if part.has_high { |
| 49 | total += part.high |
| 50 | } |
| 51 | } else { |
| 52 | total += part.value |
| 53 | } |
| 54 | } |
| 55 | t.last_signature = total |
| 56 | t.last_set = value |
| 57 | } |
| 58 | |
| 59 | struct Axis {} |
| 60 | |
| 61 | fn (a Axis) [] (part SliceIndex) int { |
| 62 | if part.is_range { |
| 63 | mut total := 100 |
| 64 | if part.has_low { |
| 65 | total += part.low * 10 |
| 66 | } |
| 67 | if part.has_high { |
| 68 | total += part.high |
| 69 | } |
| 70 | return total |
| 71 | } |
| 72 | return part.value |
| 73 | } |
| 74 | |
| 75 | fn test_operator_overloading_index() { |
| 76 | mut list := IntList{ |
| 77 | values: [3, 5, 8] |
| 78 | } |
| 79 | assert list[1] == 5 |
| 80 | list[1] = 33 |
| 81 | assert list[1] == 33 |
| 82 | list[1] += 7 |
| 83 | assert list[1] == 40 |
| 84 | list[0] *= 4 |
| 85 | assert list[0] == 12 |
| 86 | } |
| 87 | |
| 88 | fn test_operator_overloading_multi_index() { |
| 89 | mut tensor := Tensor{} |
| 90 | assert tensor[1, 2] == 3 |
| 91 | assert tensor[1..3, .., 4..] == 353 |
| 92 | tensor[2, ..3] = 7 |
| 93 | assert tensor.last_signature == 105 |
| 94 | assert tensor.last_set == 7 |
| 95 | tensor[1, 3..] += 1 |
| 96 | assert tensor.last_signature == 131 |
| 97 | assert tensor.last_set == 132 |
| 98 | |
| 99 | axis := Axis{} |
| 100 | assert axis[2] == 2 |
| 101 | assert axis[..3] == 103 |
| 102 | assert axis[4..] == 140 |
| 103 | } |
| 104 | |