-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfold.zig
41 lines (33 loc) · 1.26 KB
/
fold.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const zignite = @import("../zignite.zig");
const expect = @import("std").testing.expect;
const ConsumerType = @import("consumer_type.zig").ConsumerType;
test "fold: 2 *" {
const mul = struct {
pub fn mul(x: u32, y: u32) u32 {
return x * y;
}
}.mul;
try expect(zignite.range(u32, 1, 5).fold(u32, 2, mul) == 240);
try expect(zignite.empty(u32).fold(u32, 2, mul) == 2);
}
pub fn Fold(comptime S: type, comptime T: type, comptime reducer: fn (accumulator: S, value: T) S) type {
return struct {
accumulator: S,
pub const Type = ConsumerType(T, @This(), S);
pub inline fn init(accumulator: S) Type.State {
return .{ .accumulator = accumulator };
}
pub fn next(event: Type.Event) Type.Action {
const a = event.state.accumulator;
return switch (event.tag) {
._continue => Type.Action._await(init(a)),
._break => Type.Action._return(init(a), a),
._yield => |v| Type.Action._await(init(f(a, v))),
};
}
pub const deinit = Type.nop;
inline fn f(accumulator: S, value: T) S {
return @call(.{ .modifier = .always_inline }, reducer, .{ accumulator, value });
}
};
}