[Haskell-cafe] Being impure within a 'pure' function

Thomas Davie tom.davie at gmail.com
Wed Apr 22 05:18:04 EDT 2009


On 22 Apr 2009, at 10:38, Daniel K. wrote:

> Hello,
>
> imagine the following situation: You want to implement e.g.  
> Dijkstra's algorithm to find a shortest path between nodes u and v  
> in a graph. This algorithm relies heavily on mutating arrays, so the  
> type signature would look something like
>
> getDistance :: Graph -> Node -> Node -> IO Int
>
> Not mutating the underlying arrays would probably result in poor  
> performance. BUT: For a constant graph, the distance between two  
> nodes stays the same all the time, so in fact getDistance should be  
> a pure function!
> So here is my question: Is there a way to write functions in Haskell  
> that do some IO internally, but that are guaranteed to be side- 
> effect free? Of course one would have to make sure that the array  
> that is mutated inside getDistance must not be accessible from  
> outside the function.
>
> Is that possible? If not, wouldn't that be desirable? If not, why not?

Either, as Eugene suggested, use the ST monad, as is possible in this  
case (and much better than the solution I'm proposing), or if you  
*really* can't get out of using IO, use unsafePerformIO.  You will  
though have to provide several guarantees yourself that the type  
system would normally provide for you (hence the unsafe part - it  
should really be verifyItsSafeYourselfPerformIO).

Bob


More information about the Haskell-Cafe mailing list