v2 / vlib / v / tests / generics / generic_interface_field_test.v
79 lines · 71 sloc · 1005 bytes · 07997816d99b3f8e4ff30725f068d6048cafa595
Raw
1pub struct Range[T] {
2pub:
3 from T
4 to T
5 inclusive bool
6pub mut:
7 step T = T(1)
8 i T
9mut:
10 started bool
11}
12
13pub 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
43pub interface Iterator[T] {
44mut:
45 next() ?T
46}
47
48pub struct Zip[A, B] {
49mut:
50 a Iterator[A]
51 b Iterator[B]
52}
53
54pub struct Pair[A, B] {
55 a A
56 b B
57}
58
59pub 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
65fn 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