# Using GHCi

GHCi The ‘i’ stands for “Interactive” is GHC's interactive environment, in which Haskell expressions can be interactively evaluated and programs can be interpreted. If you're familiar with Hugs
, then you'll be right at home with GHCi. However, GHCi also has support for interactively loading compiled code, as well as supporting all except `foreign export`, at the moment the language extensions that GHC provides.

## Introduction to GHCi

Let's start with an example GHCi session. You can fire up GHCi with the command `ghci`:

    $ ghci
       ___         ___ _
      / _ \ /\  /\/ __(_)
     / /_\// /_/ / /  | |      GHC Interactive, version 6.6, for Haskell 98.
    / /_\\/ __  / /___| |      http://www.haskell.org/ghc/
    \____/\/ /_/\____/|_|      Type :? for help.

    Loading package base ... linking ... done.
    Prelude>

There may be a short pause while GHCi loads the prelude and standard libraries, after which the prompt is shown. If we follow the instructions and type `:?` for help, we get:

     Commands available from the prompt:

       <stmt>                      evaluate/run <stmt>
       :add <filename> ...         add module(s) to the current target set
       :browse [*]<module>         display the names defined by <module>
       :cd <dir>                   change directory to <dir>
       :def <cmd> <expr>           define a command :<cmd>
       :edit <file>                edit file
       :edit                       edit last module
       :help, :?                   display this list of commands
       :info [<name> ...]          display information about the given names
       :load <filename> ...        load module(s) and their dependents
       :module [+/-] [*]<mod> ...  set the context for expression evaluation
       :main [<arguments> ...]     run the main function with the given arguments
       :reload                     reload the current module set

       :set <option> ...           set options
       :set args <arg> ...         set the arguments returned by System.getArgs
       :set prog <progname>        set the value returned by System.getProgName
       :set prompt <prompt>        set the prompt used in GHCi
       :set editor <cmd>        set the command used for :edit

       :show modules               show the currently loaded modules
       :show bindings              show the current bindings made at the prompt

       :ctags [<file>]             create tags file for Vi (default: "tags")
       :etags [<file>]             create tags file for Emacs (defauilt: "TAGS")
       :type <expr>                show the type of <expr>
       :kind <type>                show the kind of <type>
       :undef <cmd>                undefine user-defined command :<cmd>
       :unset <option> ...         unset options
       :quit                       exit GHCi
       :!<command>                 run the shell command <command>

     Options for ':set' and ':unset':

        +r            revert top-level expressions after each evaluation
        +s            print timing/memory stats after each evaluation
        +t            print type after evaluation
        -<flags>      most GHC command line flags can also be set here
                             (eg. -v2, -fglasgow-exts, etc.)

We'll explain most of these commands as we go along. For Hugs users: many things work the same as in Hugs, so you should be able to get going straight away.

Haskell expressions can be typed at the prompt:

    Prelude> 1+2
    3
    Prelude> let x = 42 in x / 9
    4.666666666666667
    Prelude>

GHCi interprets the whole line as an expression to evaluate. The expression may not span several lines - as soon as you press enter, GHCi will attempt to evaluate it.

## Loading source files

Suppose we have the following Haskell source code, which we place in a file `Main.hs`:

    main = print (fac 20)

    fac 0 = 1
    fac n = n * fac (n-1)

You can save `Main.hs` anywhere you like, but if you save it somewhere other than the current directory If you started up GHCi from the command line then GHCi's current directory is the same as the current directory of the shell from which it was started. If you started GHCi from the “Start” menu in Windows, then the current directory is probably something like `C:\Documents and Settings\user name`. then we will need to change to the right directory in GHCi:

    Prelude> :cd dir

where dir is the directory (or folder) in which you saved `Main.hs`.

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 (we'll explain what the `*` means later in ). 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.

### Modules vs. filenames

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`.

The search path for finding source files is specified with the `-i` option on the GHCi command line, like so:

    ghci -idir1:...:dirn

or it can be set using the `:set` command from within GHCi (see ) Note that in GHCi, and `––make` mode, the `-i` option is used to specify the search path for source files, whereas in standard batch-compilation mode the `-i` option is used to specify the search path for interface files, see .

One consequence of the way that GHCi follows dependencies to find modules to load is that every module must have a source file. The only exception to the rule is modules that come from a package, including the `Prelude` and standard libraries such as `IO` and `Complex`. If you attempt to load a module for which GHCi can't find a source file, even if there are object and interface files for the module, you'll get an error message.

### Making changes and recompilation

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 ).

## Loading compiled code

When you load a Haskell source module into GHCi, it is normally converted to byte-code and run using the interpreter. However, interpreted code can also run alongside compiled code in GHCi; indeed, normally when GHCi starts, it loads up a compiled copy of the `base` package, which contains the `Prelude`.

Why should we want to run compiled code? Well, compiled code is roughly 10x faster than interpreted code, but takes about 2x longer to produce (perhaps longer if optimisation is on). So it pays to compile the parts of a program that aren't changing very often, and use the interpreter for the code being actively developed.

When loading up source files with `:load`, GHCi looks for any corresponding compiled object files, and will use one in preference to interpreting the source if possible. For example, suppose we have a 4-module program consisting of modules A, B, C, and D. Modules B and C both import D only, and A imports both B & C:

          A
         / \
        B   C
         \ /
          D

We can compile D, then load the whole program, like this:

    Prelude> :! ghc -c D.hs
    Prelude> :load A
    Skipping  D                ( D.hs, D.o )
    Compiling C                ( C.hs, interpreted )
    Compiling B                ( B.hs, interpreted )
    Compiling A                ( A.hs, interpreted )
    Ok, modules loaded: A, B, C, D.
    *Main>

In the messages from the compiler, we see that it skipped D, and used the object file `D.o`. The message `Skipping` module indicates that compilation for module isn't necessary, because the source and everything it depends on is unchanged since the last compilation.

At any time you can use the command `:show modules` to get a list of the modules currently loaded into GHCi:

    *Main> :show modules
    D                ( D.hs, D.o )
    C                ( C.hs, interpreted )
    B                ( B.hs, interpreted )
    A                ( A.hs, interpreted )
    *Main>

If we now modify the source of D (or pretend to: using Unix command `touch` on the source file is handy for this), the compiler will no longer be able to use the object file, because it might be out of date:

    *Main> :! touch D.hs
    *Main> :reload
    Compiling D                ( D.hs, interpreted )
    Skipping  C                ( C.hs, interpreted )
    Skipping  B                ( B.hs, interpreted )
    Skipping  A                ( A.hs, interpreted )
    Ok, modules loaded: A, B, C, D.
    *Main>

Note that module D was compiled, but in this instance because its source hadn't really changed, its interface remained the same, and the recompilation checker determined that A, B and C didn't need to be recompiled.

So let's try compiling one of the other modules:

    *Main> :! ghc -c C.hs
    *Main> :load A
    Compiling D                ( D.hs, interpreted )
    Compiling C                ( C.hs, interpreted )
    Compiling B                ( B.hs, interpreted )
    Compiling A                ( A.hs, interpreted )
    Ok, modules loaded: A, B, C, D.

We didn't get the compiled version of C! What happened? Well, in GHCi a compiled module may only depend on other compiled modules, and in this case C depends on D, which doesn't have an object file, so GHCi also rejected C's object file. Ok, so let's also compile D:

    *Main> :! ghc -c D.hs
    *Main> :reload
    Ok, modules loaded: A, B, C, D.

Nothing happened! Here's another lesson: newly compiled modules aren't picked up by `:reload`, only `:load`:

    *Main> :load A
    Skipping  D                ( D.hs, D.o )
    Skipping  C                ( C.hs, C.o )
    Compiling B                ( B.hs, interpreted )
    Compiling A                ( A.hs, interpreted )
    Ok, modules loaded: A, B, C, D.

HINT: since GHCi will only use a compiled object file if it can be sure that the compiled version is up-to-date, a good technique when working on a large program is to occasionally run `ghc ––make` to compile the whole project (say before you go for lunch :-), then continue working in the interpreter. As you modify code, the new modules will be interpreted, but the rest of the project will remain compiled.

## Interactive evaluation at the prompt

When you type an expression at the prompt, GHCi immediately evaluates and prints the result:

    Prelude> reverse "hello"
    "olleh"
    Prelude> 5+5
    10

### I/O actions at the prompt

GHCi does more than simple expression evaluation at the prompt. If you type something of type `IO a` for some `a`, then GHCi executes it as an IO-computation.

    Prelude> "hello"
    "hello"
    Prelude> putStrLn "hello"
    hello

Furthermore, GHCi will print the result of the I/O action if (and only if):

- The result type is an instance of `Show`.

- The result type is not `()`.

For example, remembering that `putStrLn :: String -> IO ()`:

    Prelude> putStrLn "hello"
    hello
    Prelude> do { putStrLn "hello"; return "yes" }
    hello
    "yes"

### Using `do-`notation at the prompt

GHCi actually accepts statements rather than just expressions at the prompt. This means you can bind values and functions to names, and use them in future expressions or statements.

The syntax of a statement accepted at the GHCi prompt is exactly the same as the syntax of a statement in a Haskell `do` expression. However, there's no monad overloading here: statements typed at the prompt must be in the `IO` monad.

    Prelude> x <- return 42
    42
    Prelude> print x
    42
    Prelude>

The statement `x <- return 42` means “execute `return 42` in the `IO` monad, and bind the result to `x`”. We can then use `x` in future statements, for example to print it as we did above.

GHCi will print the result of a statement if and only if:

- The statement is not a binding, or it is a monadic binding (`p <- e`) that binds exactly one variable.

- The variable's type is not polymorphic, is not `()`, and is an instance of `Show`

The automatic printing of binding results can be supressed with `:set -fno-print-bind-result` (this does not supress printing the result of non-binding statements).
. You might want to do this to prevent the result of binding statements from being fully evaluated by the act of printing them, for example.

Of course, you can also bind normal non-IO expressions using the `let`-statement:

    Prelude> let x = 42
    Prelude> x
    42
    Prelude>

Another important difference between the two types of binding is that the monadic bind (`p <- e`) is strict (it evaluates `e`), whereas with the `let` form, the expression isn't evaluated immediately:

    Prelude> let x = error "help!"
    Prelude> print x
    *** Exception: help!
    Prelude>

Note that `let` bindings do not automatically print the value bound, unlike monadic bindings.

Any exceptions raised during the evaluation or execution of the statement are caught and printed by the GHCi command line interface (for more information on exceptions, see the module `Control.Exception` in the libraries documentation).

Every new binding shadows any existing bindings of the same name, including entities that are in scope in the current module context.

WARNING: temporary bindings introduced at the prompt only last until the next `:load` or `:reload` command, at which time they will be simply lost. However, they do survive a change of context with `:module`: the temporary bindings just move to the new location.

HINT: To get a list of the bindings currently in scope, use the `:show bindings` command:

    Prelude> :show bindings
    x :: Int
    Prelude>

HINT: if you turn on the `+t` option, GHCi will show the type of each variable bound by a statement. For example:

    Prelude> :set +t
    Prelude> let (x:xs) = [1..]
    x :: Integer
    xs :: [Integer]

### What's really in scope at the prompt?

When you type an expression at the prompt, what identifiers and types are in scope? GHCi provides a flexible way to control exactly how the context for an expression is constructed. Let's start with the simple cases; when you start GHCi the prompt looks like this:

    Prelude>

Which indicates that everything from the module `Prelude` is currently in scope. If we now load a file into GHCi, the prompt will change:

    Prelude> :load Main.hs
    Compiling Main             ( Main.hs, interpreted )
    *Main>

The new prompt is `*Main`, which indicates that we are typing expressions in the context of the top-level of the `Main` module. Everything that is in scope at the top-level in the module `Main` we just loaded is also in scope at the prompt (probably including `Prelude`, as long as `Main` doesn't explicitly hide it).

The syntax `*module` indicates that it is the full top-level scope of module that is contributing to the scope for expressions typed at the prompt. Without the `*`, just the exports of the module are visible.

We're not limited to a single module: GHCi can combine scopes from multiple modules, in any mixture of `*` and non-`*` forms. GHCi combines the scopes from all of these modules to form the scope that is in effect at the prompt. For technical reasons, GHCi can only support the `*`-form for modules which are interpreted, so compiled modules and package modules can only contribute their exports to the current scope.

The scope is manipulated using the `:module` command. For example, if the current scope is `Prelude`, then we can bring into scope the exports from the module `IO` like so:

    Prelude> :module +IO
    Prelude IO> hPutStrLn stdout "hello\n"
    hello
    Prelude IO>

(Note: `:module` can be shortened to `:m`). The full syntax of the `:module` command is:

    :module +|- *mod1 ... *modn

Using the `+` form of the `module` commands adds modules to the current scope, and `-` removes them. Without either `+` or `-`, the current scope is replaced by the set of modules specified. Note that if you use this form and leave out `Prelude`, GHCi will assume that you really wanted the `Prelude` and add it in for you (if you don't want the `Prelude`, then ask to remove it with `:m -Prelude`).

The scope is automatically set after a `:load` command, to the most recently loaded "target" module, in a `*`-form if possible. For example, if you say `:load foo.hs bar.hs` and `bar.hs` contains module `Bar`, then the scope will be set to `*Bar` if `Bar` is interpreted, or if `Bar` is compiled it will be set to `Prelude Bar` (GHCi automatically adds `Prelude` if it isn't present and there aren't any `*`-form modules).

With multiple modules in scope, especially multiple `*`-form modules, it is likely that name clashes will occur. Haskell specifies that name clashes are only reported when an ambiguous identifier is used, and GHCi behaves in the same way for expressions typed at the prompt.

Hint: GHCi will tab-complete names that are in scope; for example, if you run GHCi and type `J<tab>` then GHCi will expand it to `Just` .

#### Qualified names

To make life slightly easier, the GHCi prompt also behaves as if there is an implicit `import qualified` declaration for every module in every package, and every module currently loaded into GHCi.

#### The `:main` command

When a program is compiled and executed, it can use the `getArgs` function to access the command-line arguments. However, we cannot simply pass the arguments to the `main` function while we are testing in ghci, as the `main` function doesn't take its directly.

Instead, we can use the `:main` command. This runs whatever `main` is in scope, with any arguments being treated the same as command-line arguments, e.g.:

    Prelude> let main = System.Environment.getArgs >>= print
    Prelude> :main foo bar
    ["foo","bar"]

### The `it` variable

Whenever an expression (or a non-binding statement, to be precise) is typed at the prompt, GHCi implicitly binds its value to the variable `it`. For example:

    Prelude> 1+2
    3
    Prelude> it * 2
    6

What actually happens is that GHCi typechecks the expression, and if it doesn't have an `IO` type, then it transforms it as follows: an expression e turns into

    let it = e;
    print it

which is then run as an IO-action.

Hence, the original expression must have a type which is an instance of the `Show` class, or GHCi will complain:

    Prelude> id

    <interactive>:1:0:
        No instance for (Show (a -> a))
          arising from use of `print' at <interactive>:1:0-1
        Possible fix: add an instance declaration for (Show (a -> a))
        In the expression: print it
        In a 'do' expression: print it

The error message contains some clues as to the transformation happening internally.

If the expression was instead of type `IO a` for some `a`, then `it` will be bound to the result of the `IO` computation, which is of type `a`. eg.:

    Prelude> Time.getClockTime
    Wed Mar 14 12:23:13 GMT 2001
    Prelude> print it
    Wed Mar 14 12:23:13 GMT 2001

The corresponding translation for an IO-typed e is

    it <- e

Note that `it` is shadowed by the new value each time you evaluate a new expression, and the old value of `it` is lost.

### Type defaulting in GHCi

Consider this GHCi session:

      ghci> reverse []

What should GHCi do? Strictly speaking, the program is ambiguous. `show (reverse [])` (which is what GHCi computes here) has type `Show a => a` and how that displays depends on the type `a`. For example:

      ghci> (reverse []) :: String
      ""
      ghci> (reverse []) :: [Int]
      []

However, it is tiresome for the user to have to specify the type, so GHCi extends Haskell's type-defaulting rules (Section 4.3.4 of the Haskell 98 Report (Revised)) as follows. The standard rules take each group of constraints `(C1 a, C2 a, ..., Cn a)` for each type variable `a`, and defaults the type variable if

- The type variable `a` appears in no other constraints

- All the classes `Ci` are standard.

- At least one of the classes `Ci` is numeric.

At the GHCi prompt, the second and third rules are relaxed as follows (differences italicised):

- All of the classes `Ci` are single-parameter type classes.

- At least one of the classes `Ci` is numeric, or is `Show`, `Eq`, or `Ord`.

The same type-default behaviour can be enabled in an ordinary Haskell module, using the flag `-fextended-default-rules`.

## Invoking GHCi

GHCi is invoked with the command `ghci` or `ghc ––interactive`. One or more modules or filenames can also be specified on the command line; this instructs GHCi to load the specified modules or filenames (and all the modules they depend on), just as if you had said `:load modules` at the GHCi prompt (see ). For example, to start GHCi and load the program whose topmost module is in the file `Main.hs`, we could say:

    $ ghci Main.hs

Most of the command-line options accepted by GHC (see ) also make sense in interactive mode. The ones that don't make sense are mostly obvious; for example, GHCi doesn't generate interface files, so options related to interface file generation won't have any effect.

### Packages

Most packages (see ) are available without needing to specify any extra flags at all: they will be automatically loaded the first time they are needed.

For non-auto packages, however, you need to request the package be loaded by using the `-package` flag:

    $ ghci -package readline
       ___         ___ _
      / _ \ /\  /\/ __(_)
     / /_\// /_/ / /  | |      GHC Interactive, version 6.6, for Haskell 98.
    / /_\\/ __  / /___| |      http://www.haskell.org/ghc/
    \____/\/ /_/\____/|_|      Type :? for help.

    Loading package base ... linking ... done.
    Loading package readline-1.0 ... linking ... done.
    Prelude>

The following command works to load new packages into a running GHCi:

    Prelude> :set -package name

But note that doing this will cause all currently loaded modules to be unloaded, and you'll be dumped back into the `Prelude`.

### Extra libraries

Extra libraries may be specified on the command line using the normal `-llib` option. (The term library here refers to libraries of foreign object code; for using libraries of Haskell source code, see .) For example, to load the “m” library:

    $ ghci -lm

On systems with `.so`-style shared libraries, the actual library loaded will the `liblib.so`. GHCi searches the following places for libraries, in this order:

- Paths specified using the `-Lpath` command-line option,

- the standard library search path for your system, which on some systems may be overridden by setting the `LD_LIBRARY_PATH` environment variable.

On systems with `.dll`-style shared libraries, the actual library loaded will be `lib.dll`. Again, GHCi will signal an error if it can't find the library.

GHCi can also load plain object files (`.o` or `.obj` depending on your platform) from the command-line. Just add the name the object file to the command line.

Ordering of `-l` options matters: a library should be mentioned before the libraries it depends on (see ).

## GHCi commands

GHCi commands all begin with ‘`:`’ and consist of a single command name followed by zero or more parameters. The command name may be abbreviated, with ambiguities being resolved in favour of the more commonly used commands.

`:add` module ...

  Add module(s) to the current target set, and perform a reload.

`:browse` `*`module ...

  Displays the identifiers defined by the module module, which must be either loaded into GHCi or be a member of a package. If the `*` symbol is placed before the module name, then all the identifiers defined in module are shown; otherwise the list is limited to the exports of module. The `*`-form is only available for modules which are interpreted; for compiled modules (including modules from packages) only the non-`*` form of `:browse` is available.

`:cd` dir

  Changes the current working directory to dir. A ‘`˜`’ symbol at the beginning of dir will be replaced by the contents of the environment variable `HOME`.

  NOTE: changing directories causes all currently loaded modules to be unloaded. This is because the search path is usually expressed using relative directories, and changing the search path in the middle of a session is not supported.

`:def` name expr

  The command `:def` name expr defines a new GHCi command `:name`, implemented by the Haskell expression expr, which must have type `String -> IO String`. When `:name args` is typed at the prompt, GHCi will run the expression `(name args)`, take the resulting `String`, and feed it back into GHCi as a new sequence of commands. Separate commands in the result must be separated by ‘`\n`’.

  That's all a little confusing, so here's a few examples. To start with, here's a new GHCi command which doesn't take any arguments or produce any results, it just outputs the current date & time:

      Prelude> let date _ = Time.getClockTime >>= print >> return ""
      Prelude> :def date date
      Prelude> :date
      Fri Mar 23 15:16:40 GMT 2001

  Here's an example of a command that takes an argument. It's a re-implementation of `:cd`:

      Prelude> let mycd d = Directory.setCurrentDirectory d >> return ""
      Prelude> :def mycd mycd
      Prelude> :mycd ..

  Or I could define a simple way to invoke “`ghc ––make Main`” in the current directory:

      Prelude> :def make (\_ -> return ":! ghc ––make Main")

  We can define a command that reads GHCi input from a file. This might be useful for creating a set of bindings that we want to repeatedly load into the GHCi session:

      Prelude> :def . readFile
      Prelude> :. cmds.ghci

  Notice that we named the command `:.`, by analogy with the ‘`.`’ Unix shell command that does the same thing.

`:edit file`

  Opens an editor to edit the file file, or the most recently loaded module if file is omitted. The editor to invoke is taken from the `EDITOR` environment variable, or a default editor on your system if `EDITOR` is not set. You can change the editor using `:set editor`.

`:help`
`:?`

  Displays a list of the available commands.

`:info` name ...

  Displays information about the given name(s). For example, if name is a class, then the class methods and their types will be printed; if name is a type constructor, then its definition will be printed; if name is a function, then its type will be printed. If name has been loaded from a source file, then GHCi will also display the location of its definition in the source.

`:load` module ...

  Recursively loads the specified modules, and all the modules they depend on. Here, each module must be a module name or filename, but may not be the name of a module in a package.

  All previously loaded modules, except package modules, are forgotten. The new set of modules is known as the target set. Note that `:load` can be used without any arguments to unload all the currently loaded modules and bindings.

  After a `:load` command, the current context is set to:

  - module, if it was loaded successfully, or

  - the most recently successfully loaded module, if any other modules were loaded as a result of the current `:load`, or

  - `Prelude` otherwise.

`:main arg1 ... argn`

  When a program is compiled and executed, it can use the `getArgs` function to access the command-line arguments. However, we cannot simply pass the arguments to the `main` function while we are testing in ghci, as the `main` function doesn't take its directly.

  Instead, we can use the `:main` command. This runs whatever `main` is in scope, with any arguments being treated the same as command-line arguments, e.g.:

      Prelude> let main = System.Environment.getArgs >>= print
      Prelude> :main foo bar
      ["foo","bar"]

`:module +|- *mod1 ... *modn`

  Sets or modifies the current context for statements typed at the prompt. See for more details.

`:quit`

  Quits GHCi. You can also quit by typing a control-D at the prompt.

`:reload`

  Attempts to reload the current target set (see `:load`) if any of the modules in the set, or any dependent module, has changed. Note that this may entail loading new modules, or dropping modules which are no longer indirectly required by the target.

`:set` option...

  Sets various options. See for a list of available options. The `:set` command by itself shows which options are currently set.

`:set` `args` arg ...

  Sets the list of arguments which are returned when the program calls `System.getArgs`
  .

`:set` `editor` cmd

  Sets the command used by `:edit` to cmd.

`:set` `prog` prog

  Sets the string to be returned when the program calls `System.getProgName`
  .

`:set` `prompt` prompt

  Sets the string to be used as the prompt in GHCi. Inside prompt, the sequence `%s` is replaced by the names of the modules currently in scope, and `%%` is replaced by `%`.

`:show bindings`

  Show the bindings made at the prompt and their types.

`:show modules`

  Show the list of modules currently load.

`:ctags` filename `:etags` filename

  Generates a “tags” file for Vi-style editors (`:ctags`) or Emacs-style editors (`etags`). If no filename is specified, the defaulit `tags` or `TAGS` is used, respectively. Tags for all the functions, constructors and types in the currently loaded modules are created. All modules must be interpreted for these commands to work.

  See also .

`:type` expression

  Infers and prints the type of expression, including explicit forall quantifiers for polymorphic types. The monomorphism restriction is not applied to the expression during type inference.

`:kind` type

  Infers and prints the kind of type. The latter can be an arbitrary type expression, including a partial application of a type constructor, such as `Either Int`.

`:undef` name

  Undefines the user-defined command name (see `:def` above).

`:unset` option...

  Unsets certain options. See for a list of available options.

`:!` command...

  Executes the shell command command.

## The `:set` command

The `:set` command sets two types of options: GHCi options, which begin with ‘`+`” and “command-line” options, which begin with ‘-’.

NOTE: at the moment, the `:set` command doesn't support any kind of quoting in its arguments: quotes will not be removed and cannot be used to group words together. For example, `:set -DFOO='BAR BAZ'` will not do what you expect.

### GHCi options

GHCi options may be set using `:set` and unset using `:unset`.

The available GHCi options are:

`+r`

  Normally, any evaluation of top-level expressions (otherwise known as CAFs or Constant Applicative Forms) in loaded modules is retained between evaluations. Turning on `+r` causes all evaluation of top-level expressions to be discarded after each evaluation (they are still retained during a single evaluation).

  This option may help if the evaluated top-level expressions are consuming large amounts of space, or if you need repeatable performance measurements.

`+s`

  Display some stats after evaluating each expression, including the elapsed time and number of bytes allocated. NOTE: the allocation figure is only accurate to the size of the storage manager's allocation area, because it is calculated at every GC. Hence, you might see values of zero if no GC has occurred.

`+t`

  Display the type of each variable bound after a statement is entered at the prompt. If the statement is a single expression, then the only variable binding will be for the variable ‘`it`’.

### Setting GHC command-line options in GHCi

Normal GHC command-line options may also be set using `:set`. For example, to turn on `-fglasgow-exts`, you would say:

    Prelude> :set -fglasgow-exts

Any GHC command-line option that is designated as dynamic (see the table in ), may be set using `:set`. To unset an option, you can set the reverse option:

    Prelude> :set -fno-glasgow-exts

lists the reverse for each option where applicable.

Certain static options (`-package`, `-I`, `-i`, and `-l` in particular) will also work, but some may not take effect until the next reload.

## The `.ghci` file

When it starts, GHCi always reads and executes commands from `$HOME/.ghci`, followed by `./.ghci`.

The `.ghci` in your home directory is most useful for turning on favourite options (eg. `:set +s`), and defining useful macros. Placing a `.ghci` file in a directory with a Haskell project is a useful way to set certain project-wide options so you don't have to type them everytime you start GHCi: eg. if your project uses GHC extensions and CPP, and has source files in three subdirectories A B and C, you might put the following lines in `.ghci`:

    :set -fglasgow-exts -cpp
    :set -iA:B:C

(Note that strictly speaking the `-i` flag is a static one, but in fact it works to set it using `:set` like this. The changes won't take effect until the next `:load`, though.)

Two command-line options control whether the `.ghci` files are read:

`-ignore-dot-ghci`

  Don't read either `./.ghci` or `$HOME/.ghci` when starting up.

`-read-dot-ghci`

  Read `.ghci` and `$HOME/.ghci`. This is normally the default, but the `-read-dot-ghci` option may be used to override a previous `-ignore-dot-ghci` option.

## FAQ and Things To Watch Out For

The interpreter can't load modules with foreign export declarations!

  Unfortunately not. We haven't implemented it yet. Please compile any offending modules by hand before loading them into GHCi.

`-O` doesn't work with GHCi!

  For technical reasons, the bytecode compiler doesn't interact well with one of the optimisation passes, so we have disabled optimisation when using the interpreter. This isn't a great loss: you'll get a much bigger win by compiling the bits of your code that need to go fast, rather than interpreting them with optimisation turned on.

Unboxed tuples don't work with GHCi

  That's right. You can always compile a module that uses unboxed tuples and load it into GHCi, however. (Incidentally the previous point, namely that `-O` is incompatible with GHCi, is because the bytecode compiler can't deal with unboxed tuples).

Concurrent threads don't carry on running when GHCi is waiting for input.

  This should work, as long as your GHCi was built with the `-threaded` switch, which is the default. Consult whoever supplied your GHCi installation.

After using `getContents`, I can't use `stdin` again until I do `:load` or `:reload`.

  This is the defined behaviour of `getContents`: it puts the stdin Handle in a state known as semi-closed, wherein any further I/O operations on it are forbidden. Because I/O state is retained between computations, the semi-closed state persists until the next `:load` or `:reload` command.

  You can make `stdin` reset itself after every evaluation by giving GHCi the command `:set +r`. This works because `stdin` is just a top-level expression that can be reverted to its unevaluated state in the same way as any other top-level expression (CAF).

I can't use Control-C to interrupt computations in GHCi on Windows.

  See .