In the general case, Purity Analysis is equivalent to solving the Halting Problem. In other words, it is impossible to statically decide, in the general case, whether a chunk of code is pure or not.
In a language like Haskell, there is no way of writing impure code in Haskell, therefore purity analysis is trivial. Here is a simple function that takes a Haskell program as an argument and tells you whether it is true or not:
isPureProgram :: a -> Bool
isPureProgram _ = True
Note, I am simplifying a couple of things here:
unsafePerformIO
and friends allow you to, well, perform unsafe I/O. It is generally assumed that you know what you are doing when you use these functions.
- Exceptions are side-effects.
- Contrary to popular belief, the
IO
monad does not allow you to write impure code in Haskell. What the IO
monad does is to write a pure program which returns a list of IO actions, which when interpreted by the runtime system result in impure computation. However, the Haskell program which generates these IO actions is still pure – it is the interpreter which is impure. But of course, the end result will be the same: an impure computation will be performed.
However, since Scala is an impure language at its core, the compiler cannot rely on similar restrictions as a Haskell compiler can, and thus cannot perform purity analysis in the general case.