Haskell this file path

Is there any way to get the path to the file where the function is defined?

For instance:

rootappdir |- Foo.hs |- Bar.hs module Foo where getThisDir :: IO Filepath getThisDir = ... prelude> getThisDir absolute/path/to/rootappdir/Foo.hs 

If possible with the even simpler :: Filepath function, this is even better. Maybe we will need to use a preprocessor?

+5
source share
2 answers

For this you need to use Template Haskell.

 {-# LANGUAGE TemplateHaskell #-} import Data.Functor import Language.Haskell.TH import System.Directory import System.FilePath filePath :: String filePath = $(do dir <- runIO getCurrentDirectory filename <- loc_filename <$> location litE $ stringL $ dir </> filename) 
+7
source

I suppose you cannot get this information at runtime. But you can get it at compile time through Template Haskell using the Language.Haskell.TH.location or qLocation .

If you need the logging function, you can use the monad-logger package . You can find an example of using qLocation there.

+3
source

Source: https://habr.com/ru/post/1202124/


All Articles