Usually data structure libraries in Haskell provides fromList
functions to convert from a list to that structure. Data.Heap is no exception. But you'll get some crazy errors when trying to use it:
Prelude Data.Heap> Data.Heap.fromList [1,2,5,7]
<interactive>:1:0:
Ambiguous type variables `t', `pol' in the constraint:
`HeapItem pol t'
arising from a use of `fromList' at <interactive>:1:0-27
Probable fix: add a type signature that fixes these type variable(s)
....
This main point here is Ambiguous type. There are several types of heaps, e.g. MaxHeap and MinHeap, which cannot be inferred from just calling fromList
. You need to tell Haskell which kind of heap you're using with a type signature:
Prelude Data.Heap> Data.Heap.fromList [1,2,5,7] :: MinHeap Int
fromList [(1,()),(2,()),(5,()),(7,())]
Other constructors e.g. singleton
, fromAscList
, etc. operate similarly.
Once you've constructed the heap, the rest are easy, e.g. to insert an item to a heap
Prelude Data.Heap> let heap = Data.Heap.fromList [1,2,5,7] :: MinHeap Int
Prelude Data.Heap> heap
fromList [(1,()),(2,()),(5,()),(7,())]
Prelude Data.Heap> Data.Heap.insert 3 heap
fromList [(1,()),(3,()),(2,()),(5,()),(7,())]
To read the top of the heap
Prelude Data.Heap> heap
fromList [(1,()),(2,()),(5,()),(7,())]
Prelude Data.Heap> viewHead heap
Just 1
etc.