Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell this file's path

Tags:

haskell

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

For example:

rootappdir
|- Foo.hs
|- Bar.hs


module Foo where

getThisDir :: IO Filepath
getThisDir = ...

prelude> getThisDir
absolute/path/to/rootappdir/Foo.hs

If it is possible with an even simpler function :: Filepath, that's even better. Maybe we would need to use the preprocessor?

like image 893
Syd Kerckhove Avatar asked Sep 09 '14 05:09

Syd Kerckhove


2 Answers

I suppose you can't get this information in run-time. But you can get it in compile-time through Template Haskell using function Language.Haskell.TH.location or qLocation.

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

like image 25
Dmitry Olshansky Avatar answered Oct 13 '22 04:10

Dmitry Olshansky


You need to use Template Haskell to do this.

{-# 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)
like image 82
snak Avatar answered Oct 13 '22 06:10

snak