From 99c32737fe07bf7dc6094a1326be418ffd00e36f Mon Sep 17 00:00:00 2001 From: Nic Gaffney Date: Tue, 28 Oct 2025 20:02:47 -0500 Subject: filter implemented --- src/filter.zig | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/filter.zig (limited to 'src/filter.zig') diff --git a/src/filter.zig b/src/filter.zig new file mode 100644 index 0000000..b9e2167 --- /dev/null +++ b/src/filter.zig @@ -0,0 +1,22 @@ +const std = @import("std"); +const typeVerify = @import("util.zig").typeVerify; + +/// ```zig +/// (fn (fn (fn (a) bool, []a) []a) +/// ``` +/// Filters a slice, only keeping items give `true` when passed into `func` +/// Type signature: `(a -> bool) -> [a] -> [a]` +/// `func` is of type `a -> bool`, where `items` is of type `[a]` +pub fn filter( + func: anytype, + items: []typeVerify(@TypeOf(func), .{ .@"fn" }).@"fn".params[0].type.?, +) []typeVerify(@TypeOf(func), .{ .@"fn" }).@"fn".params[0].type.? { + var output = items; + var i: u32 = 0; + for (items) |it| + if (func(it)) { + output[i] = it; + i = i + 1; + }; + return output[0..i]; +} -- cgit v1.2.3