Question

I wrote a function in haskell that takes a few parameters like Word32, String (ignore currying) and outputs IO Word32. Now, this is a function in the true sense: for the same inputs, the output will always be the same. There are no side-effects. The reason the function returns IO Word32 instead of Word32 is that the function updates many 32 bit Linear Feedback Shift registers (lfsr) and other registers several times in a loop in order to compute the final Word32 output.

My question is this: Given that this function effectively has no side-effects, is it possible to hide those register updates inside the function implementation so that the function returns Word32 and not IO Word32? If so, how?

Was it helpful?

Solution

Yes! Haskell can do this.

The ST monad

If you actually use mutable state (registers), that are entirely hidden from the observer outside the function, then you are in the ST monad, a monad for memory effects only. You enter the ST world via runST, and when you exit the function, all effects are guaranteed to not be visible.

It is precisely the right computational environment for working with local, mutable state.

Purely functional state: the State monad

If, however, you're not actually mutating registers or cells, but rather updating a purely functional value many times, a simpler environment is available: the State monad. This doesn't allow mutable state, but gives an illusion of local state.

IO, and unsafePerformIO

Finally, if you have local, mutable effects, like in the ST monad, but for some reason or another, you are going to need IO operations on that state (such as via an FFI call), you can simulate the ST monad, with almost as much safety, by using unsafePerformIO, instead of runST, to introduce a local IO environment. As the IO monad doesn't have nice types to enforce abstraction, you will need to manually assure yourself that the side effects will not be observable.

OTHER TIPS

If you imported that function using the FFI, just remove the IO from the return type. Else, use unsafePerformIO :: IO a -> a from System.IO.Unsafe. Please note, that this function is one of the most dangerous functions in Haskell. Don't use it, if you're not really shure about the consequences. But for your purpose, it seems okay.

Yes, this would be a legitimate use of unsafePerformIO. But it's only OK if you are really sure there are no visible effects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top