many functions in our std provide a context parameter, like
std.sort.block(comptime T: type, items:T, context: anytype, comptime lessThanFn: fn(@TypeOf(context), lhs:T, rhs: T) bool ) void
std.sort.heap(comptime T: type, items:T, context: anytype, comptime lessThanFn: fn(@TypeOf(context), lhs:T, rhs: T) bool ) void
as a contrast, the context parameter is unnecessary in many other lang.
and usually there is no need for a context even in zig;
So do we really need the context parameter in these functions?
fn block(comptime T: type, items: []T, less_than_fn: fn (lhs: T, rhs: T) bool) void {
std.sort.block(T, items, {}, struct {
fn f (_: void, lhs_: T, rhs_:T ) bool {
return less_than_fn(lhs_, rhs_);
}
}.f);
}
test "block without context"{
var items = [_]i8 {2, 1, 3, 7};
block(i8, &items, struct {
fn f(lhs: i8, rhs: i8) bool {
return lhs <= rhs;
}
}.f);
try std.testing.expectEqualSlices(i8, &[_]i8{1,2,3,7}, &items);
}
test "block with context" {
var items = [_]i8 {2, 1, 3, 7};
const S = struct {
var ctx: i8 = undefined;
fn f (lhs: i8, rhs: i8) bool {
return ctx * lhs <= ctx * rhs;
}
};
S.ctx = -1;
block(i8, &items, S.f);
try std.testing.expectEqualSlices(i8, &[_]i8{7, 3, 2, 1}, &items);
}