Created
December 8, 2019 13:19
-
-
Save MasterQ32/839bca85018331b314be8af041271521 to your computer and use it in GitHub Desktop.
How to emulate "downward" closures with Zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
fn printSliceWithFilter(comptime T: type, values: []const T, context: var, filter: fn (T, @typeOf(context)) bool) void { | |
for (values) |val, i| { | |
if (!filter(val, context)) | |
continue; | |
std.debug.warn("[{}] = {}\n", i, val); | |
} | |
} | |
pub fn main() void { | |
const values = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; | |
printSliceWithFilter(u8, values[0..], {}, struct { | |
fn filter(val: u8, _: void) bool { | |
return val < 5; | |
} | |
}.filter); | |
const strings = [_][]const u8{ | |
"Hello, World!", | |
"This is stupid.", | |
"Hi, Man!", | |
}; | |
const filterStrings = struct { | |
fn filter(val: []const u8, prefix: u8) bool { | |
return val[0] == prefix; | |
} | |
}.filter; | |
std.debug.warn("strings starting with 'H':\n"); | |
printSliceWithFilter([]const u8, strings[0..], @as(u8, 'H'), filterStrings); | |
std.debug.warn("strings starting with 'T':\n"); | |
printSliceWithFilter([]const u8, strings[0..], @as(u8, 'T'), filterStrings); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👏 👏 👏