| 1 | pub struct Range[T] { |
| 2 | pub: |
| 3 | from T |
| 4 | to T |
| 5 | inclusive bool |
| 6 | pub mut: |
| 7 | step T = T(1) |
| 8 | i T |
| 9 | mut: |
| 10 | started bool |
| 11 | } |
| 12 | |
| 13 | pub fn (mut r Range[T]) next[T]() ?T { |
| 14 | if !r.started { |
| 15 | r.started = true |
| 16 | assert r.step > 0 |
| 17 | if r.from > r.to { |
| 18 | r.step = -r.step |
| 19 | } |
| 20 | r.i = r.from |
| 21 | } |
| 22 | i := r.i |
| 23 | next_i := i + r.step |
| 24 | if r.inclusive { |
| 25 | if r.step < 0 && i < r.to { |
| 26 | return none |
| 27 | } |
| 28 | if r.step > 0 && i > r.to { |
| 29 | return none |
| 30 | } |
| 31 | } else { |
| 32 | if r.step < 0 && i <= r.to { |
| 33 | return none |
| 34 | } |
| 35 | if r.step > 0 && i >= r.to { |
| 36 | return none |
| 37 | } |
| 38 | } |
| 39 | r.i = next_i |
| 40 | return i |
| 41 | } |
| 42 | |
| 43 | pub interface Iterator[T] { |
| 44 | mut: |
| 45 | next() ?T |
| 46 | } |
| 47 | |
| 48 | pub struct Zip[A, B] { |
| 49 | mut: |
| 50 | a Iterator[A] |
| 51 | b Iterator[B] |
| 52 | } |
| 53 | |
| 54 | pub struct Pair[A, B] { |
| 55 | a A |
| 56 | b B |
| 57 | } |
| 58 | |
| 59 | pub fn (mut z Zip[A, B]) next[A, B]() ?Pair[A, B] { |
| 60 | a := z.a.next()? |
| 61 | b := z.b.next()? |
| 62 | return Pair[A, B]{a, b} |
| 63 | } |
| 64 | |
| 65 | fn test_main() { |
| 66 | mut r1 := Range{ |
| 67 | from: 5 |
| 68 | to: 10 |
| 69 | } |
| 70 | _ := Iterator[int](r1) |
| 71 | |
| 72 | mut r2 := Range{ |
| 73 | from: 10 |
| 74 | to: 5 |
| 75 | } |
| 76 | _ := Iterator[int](r2) |
| 77 | |
| 78 | _ := Zip[int, int]{} |
| 79 | } |
| 80 | |