Best pattern for callback parametrization

There is also std.mem.sortContext which is (currently) implemented via std.sort.insertionContext:

context must have methods swap and lessThan

I think std.sort is a simpler interface, while std.sortContext allows you to not only define the comparison function but also how the swap function works (which is useful when the default swap function std.mem.swap doesn’t work for what you consider to be the “element” while sorting.

Here is an example where I use a custom swap function to sort rows of a matrix that is stored as a flat slice in memory:

I think the “context with multiple methods” pattern makes sense, when you have multiple methods that need to work together and I see the “provide a single callback function” more as the special case of that when you only need a single function.

3 Likes