Using Data.Heap in Haskell or Reading Haskell Docs for Beginners

I am trying to use the Haskells Data.Heap module, but I cannot even use it with integers. The only heap I could use is the empty one, which takes no arguments.

Later I will figure out how to do this for my needs, but now I would be glad if I could check it with numbers.

+7
api data-structures haskell
source share
1 answer

Typically, Haskell's data structure libraries provide fromList functions to convert from a list to this structure. Data.Heap is no exception. But when you try to use it, you get crazy errors:

 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 an ambiguous type . There are several types of heaps, for example. MaxHeap and MinHeap, which cannot be deduced from a simple call fromList . You should tell Haskell which heap you are using with a signature like:

 Prelude Data.Heap> Data.Heap.fromList [1,2,5,7] :: MinHeap Int fromList [(1,()),(2,()),(5,()),(7,())] 

Other constructors, for example. singleton , fromAscList etc. work similarly.

Once you build a bunch, the rest is easy, for example. to insert an item into 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 

and etc.

+12
source share

All Articles