I am stuck in understanding the ‘context’ sort of Zig.
I got the no_context_sort working.
But cannot understand how to:
- change the CompareFunc declaration working for no context and with context
- get with_context_sort working.
- I know the local comparer struct cannot capture variables out of its scope.
I hope the pseudo-example is clear. And that people insanely more intellient than me can help me out ![]()
const CompareFunc = fn(_: void, a: Node, b: Node) bool;
fn recursive_sort(nodes: *Nodes, node: *const Node, context: anytype, comptime compare_func: CompareFunc) void
{
const children: get_children();
std.mem.sortUnstable(Node, children, context, compare_func);
// go recursive
}
fn no_context_sort() void
{
const comparer = struct
{
fn less_than(_: void, a: Node, b: Node) bool { return a.data < b.data; }
};
recursive_sort(nodes, root, {}, comparer.less_than);
}
fn with_context_sort() void
{
// var my_localdata: ...
const comparer = struct
{
fn less_than(?context?, a: Node, b: Node) bool { use my local data for compare }
};
recursive_sort(nodes, root, ?context?, comparer.less_than);
// recursive_sort using my_localdata ??
}