Search code examples
scalascalaz

scalaz trying to use Heap , how to override fold function


I have a case class: case class Item(id: Long, rank: Int) and i want to create a heap of Item objects. I try to create an instance of Heap[Item] but i have to override a fold function, i do not know exactly what to do and therefore i am stuck at this point

val heap = new Heap[Item] {
      override def fold[B](empty: => B, nonempty: (Int, (Item, Item) => Boolean, Tree[Ranked[Item]]) => B): B = {

      }
    }

What do i have to do to make this work so i can use the heap collection ; Thanks.


Solution

  • You shouldn't be directly calling new Heap to begin with.

    First, define an implicit Order for your Items. For example to order by rank:

    import scalaz._, Scalaz._
    
    case class Item(id: Long, rank: Int)
    object Item {
      implicit val order: Order[Item] = Order.orderBy(_.rank)
    }
    

    And then create Heaps using helper methods from the Heap companion object:

    Heap.Empty[Item]
    Heap.singleton(Item(1L, 1))
    Heap.fromData(List(Item(10L, 3), Item(20L, 2), Item(30L, 1)))