Skip to content

Heap bugs with Order #1236

@chrisokasaki

Description

@chrisokasaki

(I don't think this is likely to be a new issue, but I couldn't find any previous issues that discussed it.)

Because Heap's insert method takes the Order as an implicit parameter, it is very easy to get nonsense results by supplying incompatible orders, as shown below:

import scalaz._
import Scalaz._

def revOrd: Order[Int] = implicitly[Order[Int]].reverseOrder

val h = Heap.singleton(5).insert(7)
val h2 = h.insert(4)(revOrd)

println(h2.minimum)  // prints 5!

Of course, a programmer that does this deliberately may deserve what they get, but, because of implicits, this could easily happen accidentally when somebody creates a heap in one scope and inserts into it in a different scope that has a different implicit order defined..

Similar issues occur with the other insert methods, as well as with union.

This bug is almost certainly because the code was ported from Haskell, where a given type can only have a single Ord a instance, but Scala makes no such guarantee.

I've written a description of one approach to fixing the API of heaps to avoid this issue:
https://github.com/chrisokasaki/scads/blob/master/design/heaps.md
Fixing the issue for insert is fairly easy. Fixing the issue for union takes more work.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions