Using GHCi GHCi interpreterGHCi interactiveGHCi 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 famililar with HugsHugs , then you'll be right at home with GHCi. However, GHCi also has support for interactively loading compiled code, as well as supporting allexcept foreign export, at the moment the language extensions that GHC provides. FFIGHCi support Foreign Function InterfaceGHCi support Introduction to GHCi Let's start with an example GHCi session. You can fire up GHCi with the command ghci: $ ghci ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 5.04, for Haskell 98. / /_\\/ __ / /___| | http://www.haskell.org/ghc/ \____/\/ /_/\____/|_| Type :? for help. Loading package base ... linking ... done. Loading package haskell98 ... 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> :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 :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 :show modules show the currently loaded modules :show bindings show the current bindings made at the prompt :type <expr> show the type of <expr> :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: promptGHCi 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 directoryIf 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: :load 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 modulesand filenames filenamesof modules 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 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 mode, the option is used to specify the search path for source files, whereas in standard batch-compilation mode the 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 :reload 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 compiled codein GHCi 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 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. But that's not the whole story: if you type something of type IO a for some a, then GHCi executes it as an IO-computation, and doesn't attempt to print the result:. Prelude> "hello" "hello" Prelude> putStrLn "hello" hello 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 No instance for `Show (a -> a)' arising from use of `print' in a `do' expression pattern binding: print it The error message contains some clues as to the transformation happening internally. 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. 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. Using <literal>do-</literal>notation at the prompt do-notationin GHCi statementsin GHCi 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. Here's an example: Prelude> x <- return 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. Of course, you can also bind normal non-IO expressions using the let-statement: Prelude> let x = 42 Prelude> print x 42 Prelude> An 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> 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: +t Prelude> :set +t Prelude> let (x:xs) = [1..] x :: Integer xs :: [Integer] The <literal>it</literal> variable it 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 This is a result of the translation mentioned earlier, namely that an expression e is translated to let it = e; print it before execution, resulting in a binding for it. If the expression was 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 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 Type default Show class 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. If the expression yields a set of type constraints that are all from standard classes (Num, Eq etc.), and at least one is either a numeric class or the Show, Eq, or Ord class, GHCi will try to use one of the default types, just as described in the Report. Invoking GHCi invokingGHCi 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 packageswith GHCi 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 data ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 5.05, for Haskell 98. / /_\\/ __ / /___| | http://www.haskell.org/ghc/ \____/\/ /_/\____/|_| Type :? for help. Loading package base ... linking ... done. Loading package haskell98 ... linking ... done. Loading package lang ... linking ... done. Loading package concurrent ... linking ... done. Loading package readline ... linking ... done. Loading package unix ... linking ... done. Loading package posix ... linking ... done. Loading package util ... linking ... done. Loading package data ... 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 librarieswith GHCi 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 overriden 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. 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, as long as the abbreviation is not ambiguous. All of the builtin commands, with the exception of :unset and :undef, may be abbreviated to a single letter. :add module ... :add Add module(s) to the current target set, and perform a reload. :browse *module ... :browse 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 :cd 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 :def 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") :help :help :? :? Displays a list of the available commands. :info name ... :info 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 ... :load 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. :module +|- *mod1 ... *modn :module Sets or modifies the current context for statements typed at the prompt. See for more details. :quit :quit Quits GHCi. You can also quit by typing a control-D at the prompt. :reload :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... :set Sets various options. See for a list of available options. The :set command by itself shows which options are currently set. :set args arg ... :set Sets the list of arguments which are returned when the program calls System.getArgsgetArgs . :set prog prog :set Sets the string to be returned when the program calls System.getProgNamegetProgName . :show bindings :show bindings Show the bindings made at the prompt and their types. :show modules :show modules Show the list of modules currently load. :type expression :type 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. :undef name :undef Undefines the user-defined command name (see :def above). :unset option... :unset Unsets certain options. See for a list of available options. :! command... :! shell commandsin GHCi Executes the shell command command. The <literal>:set</literal> command :set 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 optionsGHCi GHCi options may be set using :set and unset using :unset. The available GHCi options are: +r +r CAFsin GHCi Constant Applicative FormCAFs 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 +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 +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 , 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: dynamicoptions Prelude> :set -fno-glasgow-exts lists the reverse for each option where applicable. Certain static options (, , , and in particular) will also work, but some may not take effect until the next reload. staticoptions The <filename>.ghci</filename> file .ghcifile startupfiles, GHCi 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 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: Don't read either ./.ghci or $HOME/.ghci when starting up. Read .ghci and $HOME/.ghci. This is normally the default, but the option may be used to override a previous 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. No, they don't. This is because the Haskell binding to the GNU readline library doesn't support reading from the terminal in a non-blocking way, which is required to work properly with GHC's concurrency model. 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).