Data structures as functions? (Priority Queue)

I know the Algorithms library is currently not focusing on data structures, but I don't think it's fair to compare this new library with Python's itertools module and the C++ algorithms library. Both Python and C++ support a much wider range of data structures than Swift, which makes it easier to develop focused libraries like that. On the other hand, in Swift you'd have to write your own data structures if you want a performance boost in some operations. There are many performance problems in Swift that you currently can't solve solely with what the Standard Library provides, which is not the case for Python/C++.

In any way, If we don't want to add data structures themselves, how does the Core team feel adding about some of them as Collection algorithms?

My main example and suggestion with this are Priority Queues, which is available in Python as heapq as in C++ as priority_queue. Because Swift lacks it, I would say most people's first instinct when trying to pick the first X elements in a sorted list would be to do something like this, which is very inefficient compared to a priority queue:

[5,3,7,4,7,3,8,9,2].sorted(by: <).prefix(3) // [2,3,4]

If we don't want to add the full data structure, what would the Core team think about abstracting it as a function?

[5,3,7,4,7,3,8,9,2].prefix(3, whenSortedBy: <) // [2,3,4]

Would this fall under an algorithm that has more pragmatic alternatives?

2 Likes

I think both a partial sort and a "smallest n elements" method would be welcome additions to the Algorithms package. :+1:

4 Likes

Great! Thanks for clarifying it :) I'll come up with a better proposal at the library's repo.

If there is any desire for a heap / priority queue, I'd be happy to contribute mine, although it probably belongs somewhere other than in Algorithms.

2 Likes

I think there is a real need for more useful data structures. Several times I’ve needed a priority queue or an ordered set. People end up rolling their own, often badly.

Getting the details right, especially for things like correct copy-on-write, or that ineffable swiftyness we all desire.

2 Likes

Me and @rockbruno drafted a PR

So why an open-sourced DataStructures package can't be introduced along with Algorithms? Swift is so poor in terms of data structure. The basic ones should be added at least, especially if Swift is trying to be extended to more than Apple ecosystem