Suppose we have the following Haskell source code, which we place in a file Main.hs in the current directory:
main = print (fac 20) fac 0 = 1 fac n = n * fac (n-1) |
To load a Haskell source file into GHCi, use the :load command:
Prelude> :load Main Compiling Main ( Main.hs, interpreted ) Ok, modules loaded: Main. Main> |
GHCi has loaded the Main module, and the prompt has changed to “Main>” to indicate that the current context for expressions typed at the prompt is the Main module we just loaded. So we can now type expressions involving the functions from Main.hs:
Main> fac 17 355687428096000 |
Loading a multi-module program is just as straightforward; just give the name of the “topmost” module to the :load command (hint: :load can be abbreviated to :l). The topmost module will normally be Main, but it doesn't have to be. GHCi will discover which modules are required, directly or indirectly, by the topmost module, and load them all in dependency order.
Question: How does GHC find the filename which contains module M? Answer: it looks for the file M.hs, or M.lhs. This means that for most modules, the module name must match the filename. If it doesn't, GHCi won't be able to find it.
There is one exception to this general rule: when you load a program with :load, or specify it when you invoke ghci, you can give a filename rather than a module name. This filename is loaded if it exists, and it may contain any module you like. This is particularly convenient if you have several Main modules in the same directory and you can't call them all Main.hs.
One final note: if you load a module called Main, it must contain a main function, just like in GHC.
If you make some changes to the source code and want GHCi to recompile the program, give the :reload command. The program will be recompiled as necessary, with GHCi doing its best to avoid actually recompiling modules if their external dependencies haven't changed. This is the same mechanism we use to avoid re-compiling modules in the batch compilation setting (see Section 4.9.4).