1
votes

Suppose I am given a source file called MyModule.hs and inside it the module declaration is module My.Module where ... (note: not module MyModule where ...).

I am not permitted to alter this source file or change the directory structure where the file resides.

From reading some docs about importing modules in GHCi, it looks like there are ways to import by file name (e.g. either import or :load), but not any ways to specify a module name that will be searched for in all files of the local directory.

Is there a way to import My.Module in GHCi without doing it by specifying the file's name (only the module name) and without installing it (e.g. not building it with cabal, just quickly tossing it into GHCi by module name)?

1

1 Answers

1
votes

You can't where the name contains a dot, as per the documentation

For each of these directories, it tries appending basename.extension to the directory, and checks whether the file exists. The value of basename is the module name with dots replaced by the directory separator ('/' or '\', depending on the system), and extension is a source extension (hs, lhs)...

The key part being

The value of basename is the module name with dots replaced by the directory separator ('/' or '\', depending on the system)

So your module name of My.Module will be searched for as My/Module.hs. You would need to have a directory structure like

project/
    My/
        Module.hs
    project.cabal

And from the folder project you could run

$ cabal repl
GHCi, version 7.8.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
> import My.Module

You can do this if your file is named MyModule.hs and your module name is MyModule, but it's just a special case of the rule above.

There are good reasons for this, namely that it enforces a structure to simplify your project structure and GHC's search algorithm. If this rule wasn't in place, what would stop me from having

project/
    MyModule1.hs
    MyModule2.hs

where both .hs files had the module declaration My.Module? Which one would be correct to load in GHCi if I ran import My.Module? By specifying what the filename and path is, you immediately know that the module X.Y.Z.W.Q.R.S.T is at the path X/Y/Z/W/Q/R/S/T.hs, no searching required. It reduces a lot of the ambiguity that could occur with looser module name specifications.