Get the absolute path to the original source file in Haskell

Is it possible to get the absolute path to the current source file in Haskell?

I could find only one important function: getCurrentDirectoryfrom System.Directory, but it returns the absolute path to the current directory of the calling process. ", not the path to the current file.

(I need him to read the inputs with samples that are in the same folder as the source file, if there is a better way to do this, this will be useful too!)

+4
source share
3 answers

You can use CPP. If you compile this file

{-# LANGUAGE CPP #-}
main = print __FILE__

it will infer the path to the source when you passed it to ghc, which may or may not be the full path:

/tmp $ ghc --make mypath.hs 
[1 of 1] Compiling Main             ( mypath.hs, mypath.o )
Linking mypath ...
/tmp $ ./mypath 
"mypath.hs"
/tmp $ ghc --make /tmp/mypath.hs 
Linking /tmp/mypath ...
/tmp $ ./mypath 
"/tmp/mypath.hs"
+5

file-embed. haskell /.

. , , . data-files cabal , .

+3

PseudoMacros . , C- ..

, PseudoMacros, , ghc ( , @JoachimBreitner, ),

 import PseudoMacros

 main :: IO ()
 main = putStrLn ("Hello from " ++ $__FILE__ ++ ", line " ++ show $__LINE__ ++ "!")

Hello from tmp.hs, line 5!

Hello from /tmp/tmp.hs, line 5!

, ghc.

0
source

All Articles