Search code examples
haskellghci

Module loading options in GHCi


Why does GHCi have so many different commands for loading modules into a session?

Here are ones I'm aware of, together with their rather confusing explanations from :help in ghci:

  • add [*]<mod> -- add module(s) to the current target set
  • :module [+/-] [*]<mod> -- set the context for expression evaluation
  • :load [*]<mod> -- load module(s) and their dependents
  • :reload <mod> -- reload the current module set. (Note: :help doesn't say that this can take a module argument, but it seems that it can.)
  • import Mod

What do they each do? How does the asterisk change it? Why are there so many? :(


Solution

  • There are essentially two different concepts at work here: target set and evaluation context.

    You work with the target set with :add, :load and :reload, and you work with the evaluation context with :module and import.

    The target set is the list of locally available modules that ghci is reading and compiling. Generally you would use this to specify the source that you're working on. ghci will load and compile each of these modules and any dependencies it needs.

    You use :load to reset the target set to precisely the given set of modules, and :add to add the given modules to the existing target set.

    If you specify modules in the target set with * then they will always be "bytecode-interpreted" - which means they load quickly but don't run as fast as compiled code - otherwise ghci will use a compiled object file if available and bytecode interpret if not.

    :reload on its own reloads the entire target set and dependencies. I'm not quite sure exactly what :reload <mod> does but I think it reloads <mod> and dependencies and leaves the rest untouched.

    The evaluation context controls what names are in scope at the prompt, and is fully documented here. Modules for adding to the evaluation context can either be local ones in the target set+dependencies, or be "package" ones that have been previously registered with ghc using the ghc-pkg tool (or cabal which calls that eventually). import Foo is just another way of writing :module +Foo.

    NOTE: this answer is a mixture of my intuitive understanding from my experience of using ghci and just reading the documentation and trying to integrate the two in my mind. So I may well not have got this 100% accurate!