Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize function by file contents at compile time

Is there a way to initialize a function

someText :: Text

which value will be stored in a file available at compile time?

I thought I could use TH for that, but for now I just found

embedFile :: FilePath -> Q Exp
runQ :: Quasi m => Q a -> m a

I can only unwrap Q into IO:

instance Quasi IO    
instance Quasi Q

I guess I need Identity instance of Quasi, but there is no one.


2 Answers

Isn't this just

someText :: Text
someText = $(embedStringFile "path/to/file")

Am I missing something?

(It's the TH splice itself that turns Q Exp into some other type at run-time. You shouldn't need any typeclass instances or anything...)

like image 137
MathematicalOrchid Avatar answered Mar 28 '26 07:03

MathematicalOrchid


# foo.txt
barbazblub
module FileText where
import Language.Haskell.TH

fileText :: FilePath -> Q Exp
fileText fp = LitE . StringL <$> runIO (readFile fp)
{-# LANGUAGE TemplateHaskell #-}
module Foo where

import FileText

main = putStrLn $(fileText "foo.txt")
$ runhaskell Foo.hs 
barbazblub
like image 27
leftaroundabout Avatar answered Mar 28 '26 09:03

leftaroundabout



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!