Sorting with context

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 :slight_smile:

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 ??
}

There are two distinct contexts. See: How does "context" and "lessThanFn" work in standard library sort functions? - #2 by dimdin

The first problem is you’ve hard coded the function to take a void context

//const CompareFunc = fn(_: void, a: Node, b: Node) bool;

fn recursive_sort(nodes: *Nodes, node: *const Node, context: anytype, comptime compare_func: fn(@TypeOf(context), Node, Node) bool) void {
//...
}

fn with_context_sort() void
{
    // var my_localdata: ...
    const comparer = struct
    {
        fn less_than(data: LocalDataType, a: Node, b: Node) bool { use my local data for compare }
    };
    recursive_sort(nodes, root, my_localdata, comparer.less_than);
}

Yes, I am judging your naming conventions :stuck_out_tongue:

Thanks! Got it working.
BTW: These names were only for this post :slight_smile:
I think there is not much wrong with recursive_sort that is the only original name in here.