9

I am trying to implement Dijkstra's algorithm in Haskell. I have already implemented a binary heap using a tree. In the algorithm neighbours keys of the current vertex should be updated in the heap. How can I emulate pointer to value in the heap in Haskell? How can I have fast access to elements in the heap, while the heap is changing after each operation?

  • 7
    FWIW, there are excellent priority queues on hackage, and pairing heaps are easier to implement than binary heaps but nevertheless pack quite a punch. As for mutation: Don't. There is probably a way around it, and even though mutable memory exists, using it extremely ugly to remind you that you shouldn't do it ;) –  Jun 27 '12 at 09:29
  • 7
    You will probably get better answers if you ask how to do fast Dijkstra in Haskell (which seems to be your actual problem) rather than one possible solution. – Pubby Jun 27 '12 at 09:30
  • @ElectricHedgehog, there are plenty of asymptotically optimal priority queues that can be implemented functionally, most notably binomial queues. Check out packages like [pqueue](http://hackage.haskell.org/package/pqueue). – Louis Wasserman Jun 27 '12 at 09:31
  • @delnan, the best solution without pointers I can find is to store mapping {vertex:position in the heap} and update it after each operation with heap. But it multiplies asymptotic by O(log(n)) – ElectricHedgehog Jun 27 '12 at 09:57
  • 1
    @ElectricHedgehog Before going for pointers and destructive update, make a pure version and check if it's fast enough. – augustss Jun 27 '12 at 12:45

3 Answers3

12

Check out the packages Data.IORef and Data.STRef which give you access to mutable references. Use IORefs if you also need to perform IO, and STRefs if you don't.

However, my suspicion is that you're probably doing it wrong. It is entirely possible to implement Dijkstra's algorithm without mutable state (although you need to be a little careful, as you can easily cause the asymptotic running time to blow up if you are continually recomputing function evaluations that could be cached).

Chris Taylor
  • 46,912
  • 15
  • 110
  • 154
0

You are probably looking for Data.Vector.Mutable from the vector package, which you might want to combine with the ST or IO monad.

comonad
  • 5,134
  • 2
  • 33
  • 31
0

You can use Data.FingerTree.PSQueue which supports an adjust operation to update the heap. In this case you don't need pointers to the values in the heap because you update them through their keys.

Daniel
  • 26,899
  • 12
  • 60
  • 88