Skip to content

Instantly share code, notes, and snippets.

@MasterQ32
Created December 8, 2019 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MasterQ32/839bca85018331b314be8af041271521 to your computer and use it in GitHub Desktop.
Save MasterQ32/839bca85018331b314be8af041271521 to your computer and use it in GitHub Desktop.
How to emulate "downward" closures with Zig
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);
}
Copy link

ghost commented Dec 8, 2019

👏 👏 👏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment