从文件加载纯全局变量 [英] Load pure global variable from file
问题描述
我有一个包含一些数据的文件。这些数据永远不会改变,我想让它在IO monad之外可用。我怎样才能做到这一点?
示例(请注意,这只是一个示例,我的数据不可计算):
primes.txt:
2 3 5 7 13
code.hs:
素数:: [Int]
素数=地图读数。单词。 unsafePerformIO。 readFile $primes.txt
这是合法使用 unsafePerformIO
?是否有其他选择?
您可以使用TemplateHaskell在编译时读取文件。这个文件的数据将作为一个实际的字符串存储在程序中。
在一个模块中( Text / Literal / TH.hs
在这个例子中),定义这个:
module Text.Literal.TH其中
import Language.Haskell.TH
import Language.Haskell.TH.Quote
literally :: String - > Q Exp
literally = return。 LitE。 StringL
lit :: QuasiQuoter
lit = QuasiQuoter {quoteExp = literally}
litFile :: QuasiQuoter
litFile = quoteFile lit
在你的模块中,你可以这样做:
{ - #LANGUAGE QuasiQuotes# - }
module MyModule where
import Text.Literal.TH(litFile)
primes :: [Int]
素数=地图读取。单词$ [litFile | primes.txt |]
当您编译程序时,GHC将打开 primes.txt
文件,并将其内容插入到 [litFile | primes.txt |]
部分。
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.hs
in this example), define this:
module Text.Literal.TH where
import Language.Haskell.TH
import Language.Haskell.TH.Quote
literally :: String -> Q Exp
literally = return . LitE . StringL
lit :: QuasiQuoter
lit = QuasiQuoter { quoteExp = literally }
litFile :: QuasiQuoter
litFile = quoteFile lit
In your module, you can then do:
{-# LANGUAGE QuasiQuotes #-}
module MyModule where
import Text.Literal.TH (litFile)
primes :: [Int]
primes = map read . words $ [litFile|primes.txt|]
When you compile your program, GHC will open the primes.txt
file and insert its contents where the [litFile|primes.txt|]
part is.
这篇关于从文件加载纯全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!