haskelliotemplate-haskellunsafe-perform-io

Generate a random string at compile time or run time and use it in the rest of the program


What would be the best way to do this? unsafePerformIO? Template Haskell? Something else? I have never used either of those so I don't know many of the details of using them.

Note that the program will be compiled every time it is run, so it doesn't matter if I generate the string at compile time or run time. I also need to use this string in tons of places throughout the code so I can't really do it the 'proper' way and have it be an IO action, that would require far too much other code to be put into the IO monad.


Solution

  • Using unsafeperformIO in this particular case seems to be fine as the documentation says :

    For this to be safe, the IO computation should be free of side effects and independent of its environment.

    We are not worried about the order of newStdGen.

    import System.Random
    import System.IO.Unsafe
    
    randomStr :: String
    randomStr = take 10 $ randomRs ('a','z') $ unsafePerformIO newStdGen
    
    main = do
         putStrLn randomStr
         putStrLn randomStr