3 ms·
Implement a heap that works for any type with a user-defined ordering relation (in particular, you should be able to implement both max heaps and min heaps over
by rbehrends 10y ago
Implement a heap that works for any type with a user-defined ordering relation (in particular, you should be able to implement both max heaps and min heaps over the same type by changing the ordering). The heap should allow for efficient operations to add an element, retrieve the minimum element, and to merge two heaps; merging should be able to make use of specialized bulk operations rather than just adding elements one by one. The data structure should be opaque, so that you can (e.g.) switch out binary heaps for Fibonacci heaps later on. The interface should be typesafe.
Heaps are useful, inter alia, to define efficient priority queues.
Other examples:
* Implement directed graphs using arbitrary types for nodes and edges. Graph algorithms are useful in a number of application areas.
* Implement a parser combinator library that works for various types of tokens, semantic values, and states.
General problems with lack of parametric polymorphism (where subtyping is not enough) are:
* The necessity for the client of a service to cast the result to the desired type.
* Difficulty in implementing binary operations efficiently where both operands are of the same or related types (such as the heap merge above), because you can't know for certain that they are of the same type just because they conform to the same interface.
* Lack of type safety guarantees when you're mixing incompatible instances (such as merging a min heap and a max heap over the same type).