I have a file with some data in it. This data never changes and I want to make it available outside of the IO monad. How can I do that?
Example (note that this is just an example, my data is not computable):
primes.txt:
2 3 5 7 13
code.hs:
primes :: [Int]
primes = map read . words . unsafePerformIO . readFile $ "primes.txt"
Is this a “legal” use of unsafePerformIO? Are there alternatives?
You could use TemplateHaskell to read in the file at compile time. The data of the file would then be stored as an actual string in the program.
In one module (
Text/Literal/TH.hsin this example), define this:In your module, you can then do:
When you compile your program, GHC will open the
primes.txtfile and insert its contents where the[litFile|primes.txt|]part is.