mentics
mentics

Reputation: 6999

How to get the current module name in Haskell

So, I could accomplish this by using 'topLevelSomething and removing the last token after ., or I could use moduleName 'something but that returns a Maybe...

Is there a more straightforward way to get the module name of the current context?

So, given the code:

module My.Module.Blah where
test = magicHere

What goes in that magicHere spot such that test = "My.Module.Blah" ?

Upvotes: 16

Views: 1227

Answers (3)

mentics
mentics

Reputation: 6999

Great answers. We ended up doing it this way as it seemed a little cleaner.

moduleOf 'someTopLevelThingInModule

moduleOf :: Language.Haskell.TH.Syntax.Name -> String
moduleOf = dropLastToken . show
dropLastToken :: String -> String
dropLastToken = reverse . tail . dropWhile (/= '.') . reverse

Upvotes: 5

augustss
augustss

Reputation: 23004

There's a rather roundabout way to get the current module name using Typeable.

module My.Module.Blah where
import Data.Typeable

data T = T deriving Typeable
test = init $ init $ show $ typeOf T

Upvotes: 11

Chris Kuklewicz
Chris Kuklewicz

Reputation: 8153

I thought this was a nice question, so I figured out the answer using Template Haskell:

{-# LANGUAGE TemplateHaskell #-}
module A.B.C where

import Language.Haskell.TH
import Language.Haskell.TH.Syntax

e :: String
e = $(fmap loc_module qLocation >>= \mod ->  return (LitE (StringL mod) ))

main = print e

Upvotes: 14

Related Questions