Using unsafePerformIO
in that way isn't great.
The declaration primes :: [Int]
says that primes
is a list of numbers. One particular list of numbers, that doesn't depend on anything.
In fact, however, it depends on the state of file "primes.txt" when the definition happens to be evaluated. Someone could alter this file to alter the value that primes
appears to have, which shouldn't be possible according to its type.
In the presence of a hypothetical optimisation which decides that primes
should be recomputed on demand rather than stored in memory in full (after all, its type says we'll get the same thing every time we recompute it), primes
could even appear to have two different values during a single run of the program. This is the sort of problem that can come with using unsafePerformIO
to lie to the compiler.
In practice, all of the above are probably unlikely to be a problem.
But the theoretically correct thing to do is to not make primes
a global constant (because it's not a constant). Instead, you make the computation that needs it parameterised on it (i.e. take primes
as an argument), and in the outer IO
program you read the file and then call the pure computation by passing the pure value the IO
program extracted from the file. You get the best of both worlds; you don't have to lie to the compiler, and you don't have to put your entire program in IO
. You can use constructs such as the Reader monad to avoid having to manually pass primes
around everywhere, if that helps.
So you can use unsafePerformIO
if you want to just get on with it. It's theoretically wrong, but unlikely to cause issues in practice.
Or you can refactor your program to reflect what's really going on.
Or, if primes
really is a global constant and you just don't want to literally include a huge chunk of data in your program source, you can use TemplateHaskell as demonstrated by dflemstr.
unsafePerformIO
. You can find the paper at research.microsoft.com/en-us/um/people/simonpj/papers/… – Zaporozhye