Skip to content

Commit 215f7e1

Browse files
committed
add iterator
1 parent 814b2ec commit 215f7e1

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

iterator/basic.zig

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const std = @import("std");
2+
const print = std.debug.print;
3+
4+
pub fn main() void {
5+
const string = "C,C++,Python,TypeScript";
6+
var iter = std.mem.split(u8, string, ",");
7+
8+
while (true) {
9+
const item = iter.next();
10+
if (item == null) {
11+
break;
12+
}
13+
print("{s}\n", .{item.?});
14+
}
15+
}

iterator/custom.zig

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const std = @import("std");
2+
const print = std.debug.print;
3+
4+
const MyIterator = struct {
5+
list: []const i32,
6+
exclude: i32,
7+
index: usize = 0,
8+
9+
fn next(self: *MyIterator) ?i32 {
10+
for (self.list[self.index..]) |item| {
11+
self.index += 1;
12+
if (item == self.exclude) {
13+
continue;
14+
}
15+
return item;
16+
}
17+
return null;
18+
}
19+
};
20+
21+
pub fn main() void {
22+
var iter = MyIterator{
23+
.list = &[_]i32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
24+
.exclude = 5,
25+
};
26+
27+
while (true) {
28+
const item = iter.next();
29+
if (item == null) {
30+
break;
31+
}
32+
print("{}\n", .{item.?});
33+
}
34+
}

iterator/readme.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Iterators
2+
3+
```bash
4+
$ zig run basic.zig
5+
C
6+
C++
7+
Python
8+
TypeScript
9+
```
10+
11+
```bash
12+
$ zig run custom.zig
13+
1
14+
2
15+
3
16+
4
17+
6
18+
7
19+
8
20+
9
21+
10
22+
```

0 commit comments

Comments
 (0)