1 <?xml version="1.0" encoding="iso-8859-1"?>
3 <title>Using GHCi</title>
4 <indexterm><primary>GHCi</primary></indexterm>
5 <indexterm><primary>interpreter</primary><see>GHCi</see></indexterm>
6 <indexterm><primary>interactive</primary><see>GHCi</see></indexterm>
9 <para>The ‘i’ stands for “Interactive”</para>
11 is GHC's interactive environment, in which Haskell expressions can
12 be interactively evaluated and programs can be interpreted. If
13 you're familiar with <ulink url="http://www.haskell.org/hugs/">Hugs</ulink><indexterm><primary>Hugs</primary>
14 </indexterm>, then you'll be right at home with GHCi. However, GHCi
15 also has support for interactively loading compiled code, as well as
16 supporting all<footnote><para>except <literal>foreign export</literal>, at the moment</para>
17 </footnote> the language extensions that GHC provides.</para>
18 <indexterm><primary>FFI</primary><secondary>GHCi support</secondary></indexterm>
19 <indexterm><primary>Foreign Function Interface</primary><secondary>GHCi support</secondary></indexterm>
21 <sect1 id="ghci-introduction">
22 <title>Introduction to GHCi</title>
24 <para>Let's start with an example GHCi session. You can fire up
25 GHCi with the command <literal>ghci</literal>:</para>
31 / /_\// /_/ / / | | GHC Interactive, version 6.6, for Haskell 98.
32 / /_\\/ __ / /___| | http://www.haskell.org/ghc/
33 \____/\/ /_/\____/|_| Type :? for help.
35 Loading package base ... linking ... done.
39 <para>There may be a short pause while GHCi loads the prelude and
40 standard libraries, after which the prompt is shown. If we follow
41 the instructions and type <literal>:?</literal> for help, we
45 Commands available from the prompt:
47 <stmt> evaluate/run <stmt>
48 :add <filename> ... add module(s) to the current target set
49 :browse [*]<module> display the names defined by <module>
50 :cd <dir> change directory to <dir>
51 :def <cmd> <expr> define a command :<cmd>
52 :edit <file> edit file
53 :edit edit last module
54 :help, :? display this list of commands
55 :info [<name> ...] display information about the given names
56 :load <filename> ... load module(s) and their dependents
57 :module [+/-] [*]<mod> ... set the context for expression evaluation
58 :main [<arguments> ...] run the main function with the given arguments
59 :reload reload the current module set
61 :set <option> ... set options
62 :set args <arg> ... set the arguments returned by System.getArgs
63 :set prog <progname> set the value returned by System.getProgName
64 :set prompt <prompt> set the prompt used in GHCi
65 :set editor <cmd> set the command used for :edit
67 :show modules show the currently loaded modules
68 :show bindings show the current bindings made at the prompt
70 :ctags [<file>] create tags file for Vi (default: "tags")
71 :etags [<file>] create tags file for Emacs (default: "TAGS")
72 :type <expr> show the type of <expr>
73 :kind <type> show the kind of <type>
74 :undef <cmd> undefine user-defined command :<cmd>
75 :unset <option> ... unset options
77 :!<command> run the shell command <command>
79 Options for ':set' and ':unset':
81 +r revert top-level expressions after each evaluation
82 +s print timing/memory stats after each evaluation
83 +t print type after evaluation
84 -<flags> most GHC command line flags can also be set here
85 (eg. -v2, -fglasgow-exts, etc.)
88 <para>We'll explain most of these commands as we go along. For
89 Hugs users: many things work the same as in Hugs, so you should be
90 able to get going straight away.</para>
92 <para>Haskell expressions can be typed at the prompt:</para>
93 <indexterm><primary>prompt</primary><secondary>GHCi</secondary>
99 Prelude> let x = 42 in x / 9
104 <para>GHCi interprets the whole line as an expression to evaluate.
105 The expression may not span several lines - as soon as you press
106 enter, GHCi will attempt to evaluate it.</para>
109 <sect1 id="loading-source-files">
110 <title>Loading source files</title>
112 <para>Suppose we have the following Haskell source code, which we
113 place in a file <filename>Main.hs</filename>:</para>
116 main = print (fac 20)
119 fac n = n * fac (n-1)
122 <para>You can save <filename>Main.hs</filename> anywhere you like,
123 but if you save it somewhere other than the current
124 directory<footnote><para>If you started up GHCi from the command
125 line then GHCi's current directory is the same as the current
126 directory of the shell from which it was started. If you started
127 GHCi from the “Start” menu in Windows, then the
128 current directory is probably something like
129 <filename>C:\Documents and Settings\<replaceable>user
130 name</replaceable></filename>.</para> </footnote> then we will
131 need to change to the right directory in GHCi:</para>
134 Prelude> :cd <replaceable>dir</replaceable>
137 <para>where <replaceable>dir</replaceable> is the directory (or
138 folder) in which you saved <filename>Main.hs</filename>.</para>
140 <para>To load a Haskell source file into GHCi, use the
141 <literal>:load</literal> command:</para>
142 <indexterm><primary><literal>:load</literal></primary></indexterm>
146 Compiling Main ( Main.hs, interpreted )
147 Ok, modules loaded: Main.
151 <para>GHCi has loaded the <literal>Main</literal> module, and the
152 prompt has changed to “<literal>*Main></literal>” to
153 indicate that the current context for expressions typed at the
154 prompt is the <literal>Main</literal> module we just loaded (we'll
155 explain what the <literal>*</literal> means later in <xref
156 linkend="ghci-scope"/>). So we can now type expressions involving
157 the functions from <filename>Main.hs</filename>:</para>
164 <para>Loading a multi-module program is just as straightforward;
165 just give the name of the “topmost” module to the
166 <literal>:load</literal> command (hint: <literal>:load</literal>
167 can be abbreviated to <literal>:l</literal>). The topmost module
168 will normally be <literal>Main</literal>, but it doesn't have to
169 be. GHCi will discover which modules are required, directly or
170 indirectly, by the topmost module, and load them all in dependency
173 <sect2 id="ghci-modules-filenames">
174 <title>Modules vs. filenames</title>
175 <indexterm><primary>modules</primary><secondary>and filenames</secondary></indexterm>
176 <indexterm><primary>filenames</primary><secondary>of modules</secondary></indexterm>
178 <para>Question: How does GHC find the filename which contains
179 module <replaceable>M</replaceable>? Answer: it looks for the
180 file <literal><replaceable>M</replaceable>.hs</literal>, or
181 <literal><replaceable>M</replaceable>.lhs</literal>. This means
182 that for most modules, the module name must match the filename.
183 If it doesn't, GHCi won't be able to find it.</para>
185 <para>There is one exception to this general rule: when you load
186 a program with <literal>:load</literal>, or specify it when you
187 invoke <literal>ghci</literal>, you can give a filename rather
188 than a module name. This filename is loaded if it exists, and
189 it may contain any module you like. This is particularly
190 convenient if you have several <literal>Main</literal> modules
191 in the same directory and you can't call them all
192 <filename>Main.hs</filename>.</para>
194 <para>The search path for finding source files is specified with
195 the <option>-i</option> option on the GHCi command line, like
197 <screen>ghci -i<replaceable>dir<subscript>1</subscript></replaceable>:...:<replaceable>dir<subscript>n</subscript></replaceable></screen>
199 <para>or it can be set using the <literal>:set</literal> command
200 from within GHCi (see <xref
201 linkend="ghci-cmd-line-options"/>)<footnote><para>Note that in
202 GHCi, and <option>––make</option> mode, the <option>-i</option>
203 option is used to specify the search path for
204 <emphasis>source</emphasis> files, whereas in standard
205 batch-compilation mode the <option>-i</option> option is used to
206 specify the search path for interface files, see <xref
207 linkend="search-path"/>.</para> </footnote></para>
209 <para>One consequence of the way that GHCi follows dependencies
210 to find modules to load is that every module must have a source
211 file. The only exception to the rule is modules that come from
212 a package, including the <literal>Prelude</literal> and standard
213 libraries such as <literal>IO</literal> and
214 <literal>Complex</literal>. If you attempt to load a module for
215 which GHCi can't find a source file, even if there are object
216 and interface files for the module, you'll get an error
221 <title>Making changes and recompilation</title>
222 <indexterm><primary><literal>:reload</literal></primary></indexterm>
224 <para>If you make some changes to the source code and want GHCi
225 to recompile the program, give the <literal>:reload</literal>
226 command. The program will be recompiled as necessary, with GHCi
227 doing its best to avoid actually recompiling modules if their
228 external dependencies haven't changed. This is the same
229 mechanism we use to avoid re-compiling modules in the batch
230 compilation setting (see <xref linkend="recomp"/>).</para>
234 <sect1 id="ghci-compiled">
235 <title>Loading compiled code</title>
236 <indexterm><primary>compiled code</primary><secondary>in GHCi</secondary></indexterm>
238 <para>When you load a Haskell source module into GHCi, it is
239 normally converted to byte-code and run using the interpreter.
240 However, interpreted code can also run alongside compiled code in
241 GHCi; indeed, normally when GHCi starts, it loads up a compiled
242 copy of the <literal>base</literal> package, which contains the
243 <literal>Prelude</literal>.</para>
245 <para>Why should we want to run compiled code? Well, compiled
246 code is roughly 10x faster than interpreted code, but takes about
247 2x longer to produce (perhaps longer if optimisation is on). So
248 it pays to compile the parts of a program that aren't changing
249 very often, and use the interpreter for the code being actively
252 <para>When loading up source files with <literal>:load</literal>,
253 GHCi looks for any corresponding compiled object files, and will
254 use one in preference to interpreting the source if possible. For
255 example, suppose we have a 4-module program consisting of modules
256 A, B, C, and D. Modules B and C both import D only,
257 and A imports both B & C:</para>
265 <para>We can compile D, then load the whole program, like this:</para>
267 Prelude> :! ghc -c D.hs
269 Skipping D ( D.hs, D.o )
270 Compiling C ( C.hs, interpreted )
271 Compiling B ( B.hs, interpreted )
272 Compiling A ( A.hs, interpreted )
273 Ok, modules loaded: A, B, C, D.
277 <para>In the messages from the compiler, we see that it skipped D,
278 and used the object file <filename>D.o</filename>. The message
279 <literal>Skipping</literal> <replaceable>module</replaceable>
280 indicates that compilation for <replaceable>module</replaceable>
281 isn't necessary, because the source and everything it depends on
282 is unchanged since the last compilation.</para>
284 <para>At any time you can use the command
285 <literal>:show modules</literal>
286 to get a list of the modules currently loaded
292 C ( C.hs, interpreted )
293 B ( B.hs, interpreted )
294 A ( A.hs, interpreted )
297 <para>If we now modify the source of D (or pretend to: using Unix
298 command <literal>touch</literal> on the source file is handy for
299 this), the compiler will no longer be able to use the object file,
300 because it might be out of date:</para>
305 Compiling D ( D.hs, interpreted )
306 Skipping C ( C.hs, interpreted )
307 Skipping B ( B.hs, interpreted )
308 Skipping A ( A.hs, interpreted )
309 Ok, modules loaded: A, B, C, D.
313 <para>Note that module D was compiled, but in this instance
314 because its source hadn't really changed, its interface remained
315 the same, and the recompilation checker determined that A, B and C
316 didn't need to be recompiled.</para>
318 <para>So let's try compiling one of the other modules:</para>
321 *Main> :! ghc -c C.hs
323 Compiling D ( D.hs, interpreted )
324 Compiling C ( C.hs, interpreted )
325 Compiling B ( B.hs, interpreted )
326 Compiling A ( A.hs, interpreted )
327 Ok, modules loaded: A, B, C, D.
330 <para>We didn't get the compiled version of C! What happened?
331 Well, in GHCi a compiled module may only depend on other compiled
332 modules, and in this case C depends on D, which doesn't have an
333 object file, so GHCi also rejected C's object file. Ok, so let's
334 also compile D:</para>
337 *Main> :! ghc -c D.hs
339 Ok, modules loaded: A, B, C, D.
342 <para>Nothing happened! Here's another lesson: newly compiled
343 modules aren't picked up by <literal>:reload</literal>, only
344 <literal>:load</literal>:</para>
348 Skipping D ( D.hs, D.o )
349 Skipping C ( C.hs, C.o )
350 Compiling B ( B.hs, interpreted )
351 Compiling A ( A.hs, interpreted )
352 Ok, modules loaded: A, B, C, D.
355 <para>HINT: since GHCi will only use a compiled object file if it
356 can be sure that the compiled version is up-to-date, a good technique
357 when working on a large program is to occasionally run
358 <literal>ghc ––make</literal> to compile the whole project (say
359 before you go for lunch :-), then continue working in the
360 interpreter. As you modify code, the new modules will be
361 interpreted, but the rest of the project will remain
366 <sect1 id="interactive-evaluation">
367 <title>Interactive evaluation at the prompt</title>
369 <para>When you type an expression at the prompt, GHCi immediately
370 evaluates and prints the result:
372 Prelude> reverse "hello"
379 <sect2><title>I/O actions at the prompt</title>
381 <para>GHCi does more than simple expression evaluation at the prompt.
382 If you type something of type <literal>IO a</literal> for some
383 <literal>a</literal>, then GHCi <emphasis>executes</emphasis> it
384 as an IO-computation.
388 Prelude> putStrLn "hello"
391 Furthermore, GHCi will print the result of the I/O action if (and only
394 <listitem><para>The result type is an instance of <literal>Show</literal>.</para></listitem>
395 <listitem><para>The result type is not
396 <literal>()</literal>.</para></listitem>
398 For example, remembering that <literal>putStrLn :: String -> IO ()</literal>:
400 Prelude> putStrLn "hello"
402 Prelude> do { putStrLn "hello"; return "yes" }
408 <sect2 id="ghci-stmts">
409 <title>Using <literal>do-</literal>notation at the prompt</title>
410 <indexterm><primary>do-notation</primary><secondary>in GHCi</secondary></indexterm>
411 <indexterm><primary>statements</primary><secondary>in GHCi</secondary></indexterm>
413 <para>GHCi actually accepts <firstterm>statements</firstterm>
414 rather than just expressions at the prompt. This means you can
415 bind values and functions to names, and use them in future
416 expressions or statements.</para>
418 <para>The syntax of a statement accepted at the GHCi prompt is
419 exactly the same as the syntax of a statement in a Haskell
420 <literal>do</literal> expression. However, there's no monad
421 overloading here: statements typed at the prompt must be in the
422 <literal>IO</literal> monad.
424 Prelude> x <- return 42
430 The statement <literal>x <- return 42</literal> means
431 “execute <literal>return 42</literal> in the
432 <literal>IO</literal> monad, and bind the result to
433 <literal>x</literal>”. We can then use
434 <literal>x</literal> in future statements, for example to print
435 it as we did above.</para>
437 <para>GHCi will print the result of a statement if and only if:
440 <para>The statement is not a binding, or it is a monadic binding
441 (<literal>p <- e</literal>) that binds exactly one
445 <para>The variable's type is not polymorphic, is not
446 <literal>()</literal>, and is an instance of
447 <literal>Show</literal></para>
450 The automatic printing of binding results can be supressed with
451 <option>:set -fno-print-bind-result</option> (this does not
452 supress printing the result of non-binding statements).
453 <indexterm><primary><option>-fno-print-bind-result</option></primary></indexterm><indexterm><primary><option>-fprint-bind-result</option></primary></indexterm>.
454 You might want to do this to prevent the result of binding
455 statements from being fully evaluated by the act of printing
456 them, for example.</para>
458 <para>Of course, you can also bind normal non-IO expressions
459 using the <literal>let</literal>-statement:</para>
466 <para>Another important difference between the two types of binding
467 is that the monadic bind (<literal>p <- e</literal>) is
468 <emphasis>strict</emphasis> (it evaluates <literal>e</literal>),
469 whereas with the <literal>let</literal> form, the expression
470 isn't evaluated immediately:</para>
472 Prelude> let x = error "help!"
478 <para>Note that <literal>let</literal> bindings do not automatically
479 print the value bound, unlike monadic bindings.</para>
481 <para>Any exceptions raised during the evaluation or execution
482 of the statement are caught and printed by the GHCi command line
483 interface (for more information on exceptions, see the module
484 <literal>Control.Exception</literal> in the libraries
485 documentation).</para>
487 <para>Every new binding shadows any existing bindings of the
488 same name, including entities that are in scope in the current
489 module context.</para>
491 <para>WARNING: temporary bindings introduced at the prompt only
492 last until the next <literal>:load</literal> or
493 <literal>:reload</literal> command, at which time they will be
494 simply lost. However, they do survive a change of context with
495 <literal>:module</literal>: the temporary bindings just move to
496 the new location.</para>
498 <para>HINT: To get a list of the bindings currently in scope, use the
499 <literal>:show bindings</literal> command:</para>
502 Prelude> :show bindings
506 <para>HINT: if you turn on the <literal>+t</literal> option,
507 GHCi will show the type of each variable bound by a statement.
509 <indexterm><primary><literal>+t</literal></primary></indexterm>
512 Prelude> let (x:xs) = [1..]
519 <sect2 id="ghci-scope">
520 <title>What's really in scope at the prompt?</title>
522 <para>When you type an expression at the prompt, what
523 identifiers and types are in scope? GHCi provides a flexible
524 way to control exactly how the context for an expression is
525 constructed. Let's start with the simple cases; when you start
526 GHCi the prompt looks like this:</para>
528 <screen>Prelude></screen>
530 <para>Which indicates that everything from the module
531 <literal>Prelude</literal> is currently in scope. If we now
532 load a file into GHCi, the prompt will change:</para>
535 Prelude> :load Main.hs
536 Compiling Main ( Main.hs, interpreted )
540 <para>The new prompt is <literal>*Main</literal>, which
541 indicates that we are typing expressions in the context of the
542 top-level of the <literal>Main</literal> module. Everything
543 that is in scope at the top-level in the module
544 <literal>Main</literal> we just loaded is also in scope at the
545 prompt (probably including <literal>Prelude</literal>, as long
546 as <literal>Main</literal> doesn't explicitly hide it).</para>
549 <literal>*<replaceable>module</replaceable></literal> indicates
550 that it is the full top-level scope of
551 <replaceable>module</replaceable> that is contributing to the
552 scope for expressions typed at the prompt. Without the
553 <literal>*</literal>, just the exports of the module are
556 <para>We're not limited to a single module: GHCi can combine
557 scopes from multiple modules, in any mixture of
558 <literal>*</literal> and non-<literal>*</literal> forms. GHCi
559 combines the scopes from all of these modules to form the scope
560 that is in effect at the prompt. For technical reasons, GHCi
561 can only support the <literal>*</literal>-form for modules which
562 are interpreted, so compiled modules and package modules can
563 only contribute their exports to the current scope.</para>
565 <para>The scope is manipulated using the
566 <literal>:module</literal> command. For example, if the current
567 scope is <literal>Prelude</literal>, then we can bring into
568 scope the exports from the module <literal>IO</literal> like
573 Prelude IO> hPutStrLn stdout "hello\n"
578 <para>(Note: <literal>:module</literal> can be shortened to
579 <literal>:m</literal>). The full syntax of the
580 <literal>:module</literal> command is:</para>
583 :module <optional>+|-</optional> <optional>*</optional><replaceable>mod<subscript>1</subscript></replaceable> ... <optional>*</optional><replaceable>mod<subscript>n</subscript></replaceable>
586 <para>Using the <literal>+</literal> form of the
587 <literal>module</literal> commands adds modules to the current
588 scope, and <literal>-</literal> removes them. Without either
589 <literal>+</literal> or <literal>-</literal>, the current scope
590 is replaced by the set of modules specified. Note that if you
591 use this form and leave out <literal>Prelude</literal>, GHCi
592 will assume that you really wanted the
593 <literal>Prelude</literal> and add it in for you (if you don't
594 want the <literal>Prelude</literal>, then ask to remove it with
595 <literal>:m -Prelude</literal>).</para>
597 <para>The scope is automatically set after a
598 <literal>:load</literal> command, to the most recently loaded
599 "target" module, in a <literal>*</literal>-form if possible.
600 For example, if you say <literal>:load foo.hs bar.hs</literal>
601 and <filename>bar.hs</filename> contains module
602 <literal>Bar</literal>, then the scope will be set to
603 <literal>*Bar</literal> if <literal>Bar</literal> is
604 interpreted, or if <literal>Bar</literal> is compiled it will be
605 set to <literal>Prelude Bar</literal> (GHCi automatically adds
606 <literal>Prelude</literal> if it isn't present and there aren't
607 any <literal>*</literal>-form modules).</para>
609 <para>With multiple modules in scope, especially multiple
610 <literal>*</literal>-form modules, it is likely that name
611 clashes will occur. Haskell specifies that name clashes are
612 only reported when an ambiguous identifier is used, and GHCi
613 behaves in the same way for expressions typed at the
617 Hint: GHCi will tab-complete names that are in scope; for
618 example, if you run GHCi and type <literal>J<tab></literal>
619 then GHCi will expand it to <literal>Just </literal>.
623 <title>Qualified names</title>
625 <para>To make life slightly easier, the GHCi prompt also
626 behaves as if there is an implicit <literal>import
627 qualified</literal> declaration for every module in every
628 package, and every module currently loaded into GHCi.</para>
632 <title>The <literal>:main</literal> command</title>
635 When a program is compiled and executed, it can use the
636 <literal>getArgs</literal> function to access the
637 command-line arguments.
638 However, we cannot simply pass the arguments to the
639 <literal>main</literal> function while we are testing in ghci,
640 as the <literal>main</literal> function doesn't take its
645 Instead, we can use the <literal>:main</literal> command.
646 This runs whatever <literal>main</literal> is in scope, with
647 any arguments being treated the same as command-line arguments,
652 Prelude> let main = System.Environment.getArgs >>= print
653 Prelude> :main foo bar
662 <title>The <literal>it</literal> variable</title>
663 <indexterm><primary><literal>it</literal></primary>
666 <para>Whenever an expression (or a non-binding statement, to be
667 precise) is typed at the prompt, GHCi implicitly binds its value
668 to the variable <literal>it</literal>. For example:</para>
675 <para>What actually happens is that GHCi typechecks the
676 expression, and if it doesn't have an <literal>IO</literal> type,
677 then it transforms it as follows: an expression
678 <replaceable>e</replaceable> turns into
680 let it = <replaceable>e</replaceable>;
683 which is then run as an IO-action.</para>
685 <para>Hence, the original expression must have a type which is an
686 instance of the <literal>Show</literal> class, or GHCi will
692 <interactive>:1:0:
693 No instance for (Show (a -> a))
694 arising from use of `print' at <interactive>:1:0-1
695 Possible fix: add an instance declaration for (Show (a -> a))
696 In the expression: print it
697 In a 'do' expression: print it
700 <para>The error message contains some clues as to the
701 transformation happening internally.</para>
703 <para>If the expression was instead of type <literal>IO a</literal> for
704 some <literal>a</literal>, then <literal>it</literal> will be
705 bound to the result of the <literal>IO</literal> computation,
706 which is of type <literal>a</literal>. eg.:</para>
708 Prelude> Time.getClockTime
709 Wed Mar 14 12:23:13 GMT 2001
711 Wed Mar 14 12:23:13 GMT 2001
714 <para>The corresponding translation for an IO-typed
715 <replaceable>e</replaceable> is
717 it <- <replaceable>e</replaceable>
721 <para>Note that <literal>it</literal> is shadowed by the new
722 value each time you evaluate a new expression, and the old value
723 of <literal>it</literal> is lost.</para>
727 <sect2 id="extended-default-rules">
728 <title>Type defaulting in GHCi</title>
729 <indexterm><primary>Type default</primary></indexterm>
730 <indexterm><primary><literal>Show</literal> class</primary></indexterm>
732 Consider this GHCi session:
736 What should GHCi do? Strictly speaking, the program is ambiguous. <literal>show (reverse [])</literal>
737 (which is what GHCi computes here) has type <literal>Show a => a</literal> and how that displays depends
738 on the type <literal>a</literal>. For example:
740 ghci> (reverse []) :: String
742 ghci> (reverse []) :: [Int]
745 However, it is tiresome for the user to have to specify the type, so GHCi extends Haskell's type-defaulting
746 rules (Section 4.3.4 of the Haskell 98 Report (Revised)) as follows. The
747 standard rules take each group of constraints <literal>(C1 a, C2 a, ..., Cn
748 a)</literal> for each type variable <literal>a</literal>, and defaults the
753 The type variable <literal>a</literal> appears in no
759 All the classes <literal>Ci</literal> are standard.
764 At least one of the classes <literal>Ci</literal> is
769 At the GHCi prompt, or with GHC if the
770 <literal>-fextended-default-rules</literal> flag is given,
771 the following additional differences apply:
775 Rule 2 above is relaxed thus:
776 <emphasis>All</emphasis> of the classes
777 <literal>Ci</literal> are single-parameter type classes.
782 Rule 3 above is relaxed this:
783 At least one of the classes <literal>Ci</literal> is
784 numeric, <emphasis>or is <literal>Show</literal>,
785 <literal>Eq</literal>, or
786 <literal>Ord</literal></emphasis>.
791 The unit type <literal>()</literal> is added to the
792 start of the standard list of types which are tried when
793 doing type defaulting.
797 The last point means that, for example, this program:
804 def :: (Num a, Enum a) => a
807 prints <literal>()</literal> rather than <literal>0</literal> as the
808 type is defaulted to <literal>()</literal> rather than
809 <literal>Integer</literal>.
812 The motivation for the change is that it means <literal>IO a</literal>
813 actions default to <literal>IO ()</literal>, which in turn means that
814 ghci won't try to print a result when running them. This is
815 particularly important for <literal>printf</literal>, which has an
816 instance that returns <literal>IO a</literal>.
817 However, it is only able to return
818 <literal>undefined</literal>
819 (the reason for the instance having this type is to not require
820 extensions to the class system), so if the type defaults to
821 <literal>Integer</literal> then ghci gives an error when running a
827 <sect1 id="ghci-invocation">
828 <title>Invoking GHCi</title>
829 <indexterm><primary>invoking</primary><secondary>GHCi</secondary></indexterm>
830 <indexterm><primary><option>––interactive</option></primary></indexterm>
832 <para>GHCi is invoked with the command <literal>ghci</literal> or
833 <literal>ghc ––interactive</literal>. One or more modules or
834 filenames can also be specified on the command line; this
835 instructs GHCi to load the specified modules or filenames (and all
836 the modules they depend on), just as if you had said
837 <literal>:load <replaceable>modules</replaceable></literal> at the
838 GHCi prompt (see <xref linkend="ghci-commands"/>). For example, to
839 start GHCi and load the program whose topmost module is in the
840 file <literal>Main.hs</literal>, we could say:</para>
846 <para>Most of the command-line options accepted by GHC (see <xref
847 linkend="using-ghc"/>) also make sense in interactive mode. The ones
848 that don't make sense are mostly obvious; for example, GHCi
849 doesn't generate interface files, so options related to interface
850 file generation won't have any effect.</para>
853 <title>Packages</title>
854 <indexterm><primary>packages</primary><secondary>with GHCi</secondary></indexterm>
856 <para>Most packages (see <xref linkend="using-packages"/>) are
857 available without needing to specify any extra flags at all:
858 they will be automatically loaded the first time they are
861 <para>For non-auto packages, however, you need to request the
862 package be loaded by using the <literal>-package</literal> flag:</para>
865 $ ghci -package readline
868 / /_\// /_/ / / | | GHC Interactive, version 6.6, for Haskell 98.
869 / /_\\/ __ / /___| | http://www.haskell.org/ghc/
870 \____/\/ /_/\____/|_| Type :? for help.
872 Loading package base ... linking ... done.
873 Loading package readline-1.0 ... linking ... done.
877 <para>The following command works to load new packages into a
881 Prelude> :set -package <replaceable>name</replaceable>
884 <para>But note that doing this will cause all currently loaded
885 modules to be unloaded, and you'll be dumped back into the
886 <literal>Prelude</literal>.</para>
890 <title>Extra libraries</title>
891 <indexterm><primary>libraries</primary><secondary>with GHCi</secondary></indexterm>
893 <para>Extra libraries may be specified on the command line using
894 the normal <literal>-l<replaceable>lib</replaceable></literal>
895 option. (The term <emphasis>library</emphasis> here refers to
896 libraries of foreign object code; for using libraries of Haskell
897 source code, see <xref linkend="ghci-modules-filenames"/>.) For
898 example, to load the “m” library:</para>
904 <para>On systems with <literal>.so</literal>-style shared
905 libraries, the actual library loaded will the
906 <filename>lib<replaceable>lib</replaceable>.so</filename>. GHCi
907 searches the following places for libraries, in this order:</para>
911 <para>Paths specified using the
912 <literal>-L<replaceable>path</replaceable></literal>
913 command-line option,</para>
916 <para>the standard library search path for your system,
917 which on some systems may be overridden by setting the
918 <literal>LD_LIBRARY_PATH</literal> environment
923 <para>On systems with <literal>.dll</literal>-style shared
924 libraries, the actual library loaded will be
925 <filename><replaceable>lib</replaceable>.dll</filename>. Again,
926 GHCi will signal an error if it can't find the library.</para>
928 <para>GHCi can also load plain object files
929 (<literal>.o</literal> or <literal>.obj</literal> depending on
930 your platform) from the command-line. Just add the name the
931 object file to the command line.</para>
933 <para>Ordering of <option>-l</option> options matters: a library
934 should be mentioned <emphasis>before</emphasis> the libraries it
935 depends on (see <xref linkend="options-linker"/>).</para>
940 <sect1 id="ghci-commands">
941 <title>GHCi commands</title>
943 <para>GHCi commands all begin with
944 ‘<literal>:</literal>’ and consist of a single command
945 name followed by zero or more parameters. The command name may be
946 abbreviated, with ambiguities being resolved in favour of the more
947 commonly used commands.</para>
952 <literal>:add</literal> <replaceable>module</replaceable> ...
953 <indexterm><primary><literal>:add</literal></primary></indexterm>
956 <para>Add <replaceable>module</replaceable>(s) to the
957 current <firstterm>target set</firstterm>, and perform a
964 <literal>:breakpoint</literal> <replaceable>list|add|continue|del|stop|step</replaceable> ...
965 <indexterm><primary><literal>:breakpoint</literal></primary></indexterm>
968 <para>Permits to add, delete or list the breakpoints in a debugging session.
975 <literal>:browse</literal> <optional><literal>*</literal></optional><replaceable>module</replaceable> ...
976 <indexterm><primary><literal>:browse</literal></primary></indexterm>
979 <para>Displays the identifiers defined by the module
980 <replaceable>module</replaceable>, which must be either
981 loaded into GHCi or be a member of a package. If the
982 <literal>*</literal> symbol is placed before the module
983 name, then <emphasis>all</emphasis> the identifiers defined
984 in <replaceable>module</replaceable> are shown; otherwise
985 the list is limited to the exports of
986 <replaceable>module</replaceable>. The
987 <literal>*</literal>-form is only available for modules
988 which are interpreted; for compiled modules (including
989 modules from packages) only the non-<literal>*</literal>
990 form of <literal>:browse</literal> is available.</para>
996 <literal>:cd</literal> <replaceable>dir</replaceable>
997 <indexterm><primary><literal>:cd</literal></primary></indexterm>
1000 <para>Changes the current working directory to
1001 <replaceable>dir</replaceable>. A
1002 ‘<literal>˜</literal>’ symbol at the
1003 beginning of <replaceable>dir</replaceable> will be replaced
1004 by the contents of the environment variable
1005 <literal>HOME</literal>.</para>
1007 <para>NOTE: changing directories causes all currently loaded
1008 modules to be unloaded. This is because the search path is
1009 usually expressed using relative directories, and changing
1010 the search path in the middle of a session is not
1017 <literal>:continue</literal>
1018 <indexterm><primary><literal>:continue</literal></primary></indexterm>
1020 <listitem><para>Shortcut to <literal>:breakpoint continue</literal></para>
1026 <literal>:def</literal> <replaceable>name</replaceable> <replaceable>expr</replaceable>
1027 <indexterm><primary><literal>:def</literal></primary></indexterm>
1030 <para>The command <literal>:def</literal>
1031 <replaceable>name</replaceable>
1032 <replaceable>expr</replaceable> defines a new GHCi command
1033 <literal>:<replaceable>name</replaceable></literal>,
1034 implemented by the Haskell expression
1035 <replaceable>expr</replaceable>, which must have type
1036 <literal>String -> IO String</literal>. When
1037 <literal>:<replaceable>name</replaceable>
1038 <replaceable>args</replaceable></literal> is typed at the
1039 prompt, GHCi will run the expression
1040 <literal>(<replaceable>name</replaceable>
1041 <replaceable>args</replaceable>)</literal>, take the
1042 resulting <literal>String</literal>, and feed it back into
1043 GHCi as a new sequence of commands. Separate commands in
1044 the result must be separated by
1045 ‘<literal>\n</literal>’.</para>
1047 <para>That's all a little confusing, so here's a few
1048 examples. To start with, here's a new GHCi command which
1049 doesn't take any arguments or produce any results, it just
1050 outputs the current date & time:</para>
1053 Prelude> let date _ = Time.getClockTime >>= print >> return ""
1054 Prelude> :def date date
1056 Fri Mar 23 15:16:40 GMT 2001
1059 <para>Here's an example of a command that takes an argument.
1060 It's a re-implementation of <literal>:cd</literal>:</para>
1063 Prelude> let mycd d = Directory.setCurrentDirectory d >> return ""
1064 Prelude> :def mycd mycd
1068 <para>Or I could define a simple way to invoke
1069 “<literal>ghc ––make Main</literal>” in the
1070 current directory:</para>
1073 Prelude> :def make (\_ -> return ":! ghc ––make Main")
1076 <para>We can define a command that reads GHCi input from a
1077 file. This might be useful for creating a set of bindings
1078 that we want to repeatedly load into the GHCi session:</para>
1081 Prelude> :def . readFile
1082 Prelude> :. cmds.ghci
1085 <para>Notice that we named the command
1086 <literal>:.</literal>, by analogy with the
1087 ‘<literal>.</literal>’ Unix shell command that
1088 does the same thing.</para>
1094 <literal>:edit <optional><replaceable>file</replaceable></optional></literal>
1095 <indexterm><primary><literal>:edit</literal></primary></indexterm>
1098 <para>Opens an editor to edit the file
1099 <replaceable>file</replaceable>, or the most recently loaded
1100 module if <replaceable>file</replaceable> is omitted. The
1101 editor to invoke is taken from the <literal>EDITOR</literal>
1102 environment variable, or a default editor on your system if
1103 <literal>EDITOR</literal> is not set. You can change the
1104 editor using <literal>:set editor</literal>.</para>
1110 <literal>:help</literal>
1111 <indexterm><primary><literal>:help</literal></primary></indexterm>
1114 <literal>:?</literal>
1115 <indexterm><primary><literal>:?</literal></primary></indexterm>
1118 <para>Displays a list of the available commands.</para>
1124 <literal>:info</literal> <replaceable>name</replaceable> ...
1125 <indexterm><primary><literal>:info</literal></primary></indexterm>
1128 <para>Displays information about the given name(s). For
1129 example, if <replaceable>name</replaceable> is a class, then
1130 the class methods and their types will be printed; if
1131 <replaceable>name</replaceable> is a type constructor, then
1132 its definition will be printed; if
1133 <replaceable>name</replaceable> is a function, then its type
1134 will be printed. If <replaceable>name</replaceable> has
1135 been loaded from a source file, then GHCi will also display
1136 the location of its definition in the source.</para>
1142 <literal>:load</literal> <replaceable>module</replaceable> ...
1143 <indexterm><primary><literal>:load</literal></primary></indexterm>
1146 <para>Recursively loads the specified
1147 <replaceable>module</replaceable>s, and all the modules they
1148 depend on. Here, each <replaceable>module</replaceable>
1149 must be a module name or filename, but may not be the name
1150 of a module in a package.</para>
1152 <para>All previously loaded modules, except package modules,
1153 are forgotten. The new set of modules is known as the
1154 <firstterm>target set</firstterm>. Note that
1155 <literal>:load</literal> can be used without any arguments
1156 to unload all the currently loaded modules and
1159 <para>After a <literal>:load</literal> command, the current
1160 context is set to:</para>
1164 <para><replaceable>module</replaceable>, if it was loaded
1165 successfully, or</para>
1168 <para>the most recently successfully loaded module, if
1169 any other modules were loaded as a result of the current
1170 <literal>:load</literal>, or</para>
1173 <para><literal>Prelude</literal> otherwise.</para>
1181 <literal>:main <replaceable>arg<subscript>1</subscript></replaceable> ... <replaceable>arg<subscript>n</subscript></replaceable></literal>
1182 <indexterm><primary><literal>:main</literal></primary></indexterm>
1186 When a program is compiled and executed, it can use the
1187 <literal>getArgs</literal> function to access the
1188 command-line arguments.
1189 However, we cannot simply pass the arguments to the
1190 <literal>main</literal> function while we are testing in ghci,
1191 as the <literal>main</literal> function doesn't take its
1196 Instead, we can use the <literal>:main</literal> command.
1197 This runs whatever <literal>main</literal> is in scope, with
1198 any arguments being treated the same as command-line arguments,
1203 Prelude> let main = System.Environment.getArgs >>= print
1204 Prelude> :main foo bar
1213 <literal>:module <optional>+|-</optional> <optional>*</optional><replaceable>mod<subscript>1</subscript></replaceable> ... <optional>*</optional><replaceable>mod<subscript>n</subscript></replaceable></literal>
1214 <indexterm><primary><literal>:module</literal></primary></indexterm>
1217 <para>Sets or modifies the current context for statements
1218 typed at the prompt. See <xref linkend="ghci-scope"/> for
1219 more details.</para>
1225 <literal>:print </literal> <replaceable>names</replaceable> ...
1226 <indexterm><primary><literal>:print</literal></primary></indexterm>
1229 <para> Prints a semievaluated value without forcing its evaluation.
1230 <literal>:print </literal> works just like <literal>:sprint</literal> but additionally,
1231 <literal>:print</literal> binds the unevaluated parts -called
1232 <quote>suspensions</quote>-
1233 to names which you can play with. For example:
1235 Prelude> let li = map Just [1..5]
1239 li - (_t1::[Maybe Integer])
1245 li - Just 1 : (_t2::[Maybe Integer])
1249 li - [Just 1,_,_,_,Just 5]
1251 li - [Just 1,(_t3::Maybe Integer),(_t4::Maybe Integer),(_t5::Maybe Integer),Just 4]
1255 li - [Just 1,(_t6::Maybe Integer),Just 3,(_t7::Maybe Integer),Just 4]
1257 The example uses <literal>:print</literal> and <literal>:sprint</literal>
1258 to help us observe how the <literal>li</literal> variable is evaluated progressively as we operate
1259 with it. Note for instance how <quote>last</quote> traverses all the elements of
1260 the list to compute its result, but without evaluating the individual elements.
1267 <literal>:quit</literal>
1268 <indexterm><primary><literal>:quit</literal></primary></indexterm>
1271 <para>Quits GHCi. You can also quit by typing a control-D
1272 at the prompt.</para>
1278 <literal>:reload</literal>
1279 <indexterm><primary><literal>:reload</literal></primary></indexterm>
1282 <para>Attempts to reload the current target set (see
1283 <literal>:load</literal>) if any of the modules in the set,
1284 or any dependent module, has changed. Note that this may
1285 entail loading new modules, or dropping modules which are no
1286 longer indirectly required by the target.</para>
1292 <literal>:set</literal> <optional><replaceable>option</replaceable>...</optional>
1293 <indexterm><primary><literal>:set</literal></primary></indexterm>
1296 <para>Sets various options. See <xref linkend="ghci-set"/>
1297 for a list of available options. The
1298 <literal>:set</literal> command by itself shows which
1299 options are currently set.</para>
1305 <literal>:set</literal> <literal>args</literal> <replaceable>arg</replaceable> ...
1306 <indexterm><primary><literal>:set args</literal></primary></indexterm>
1309 <para>Sets the list of arguments which are returned when the
1310 program calls <literal>System.getArgs</literal><indexterm><primary>getArgs</primary>
1311 </indexterm>.</para>
1317 <literal>:set</literal> <literal>editor</literal> <replaceable>cmd</replaceable>
1320 <para>Sets the command used by <literal>:edit</literal> to
1321 <replaceable>cmd</replaceable>.</para>
1327 <literal>:set</literal> <literal>prog</literal> <replaceable>prog</replaceable>
1328 <indexterm><primary><literal>:set prog</literal></primary></indexterm>
1331 <para>Sets the string to be returned when the program calls
1332 <literal>System.getProgName</literal><indexterm><primary>getProgName</primary>
1333 </indexterm>.</para>
1339 <literal>:set</literal> <literal>prompt</literal> <replaceable>prompt</replaceable>
1342 <para>Sets the string to be used as the prompt in GHCi.
1343 Inside <replaceable>prompt</replaceable>, the sequence
1344 <literal>%s</literal> is replaced by the names of the
1345 modules currently in scope, and <literal>%%</literal> is
1346 replaced by <literal>%</literal>.</para>
1352 <literal>:show bindings</literal>
1353 <indexterm><primary><literal>:show bindings</literal></primary></indexterm>
1356 <para>Show the bindings made at the prompt and their
1363 <literal>:show modules</literal>
1364 <indexterm><primary><literal>:show modules</literal></primary></indexterm>
1367 <para>Show the list of modules currently load.</para>
1372 <literal>:sprint</literal>
1373 <indexterm><primary><literal>:sprint</literal></primary></indexterm>
1376 <para>Prints a semievaluated value without forcing its evaluation.
1377 <literal>:sprint</literal> and its sibling <literal>:print</literal>
1378 are very useful to observe how lazy evaluation works in your code. For example:
1380 Prelude> let li = map Just [1..5]
1390 li - [Just 1,_,_,_,Just 5]
1392 The example uses <literal>:sprint</literal> to help us observe how the <literal>li</literal> variable is evaluated progressively as we operate
1393 with it. Note for instance how <quote>last</quote> traverses all the elements of
1394 the list to compute its result, but without evaluating the individual elements.
1400 <literal>:ctags</literal> <optional><replaceable>filename</replaceable></optional>
1401 <literal>:etags</literal> <optional><replaceable>filename</replaceable></optional>
1402 <indexterm><primary><literal>:etags</literal></primary>
1404 <indexterm><primary><literal>:etags</literal></primary>
1408 <para>Generates a “tags” file for Vi-style editors
1409 (<literal>:ctags</literal>) or Emacs-style editors (<literal>etags</literal>). If
1410 no filename is specified, the defaulit <filename>tags</filename> or
1411 <filename>TAGS</filename> is
1412 used, respectively. Tags for all the functions, constructors and
1413 types in the currently loaded modules are created. All modules must
1414 be interpreted for these commands to work.</para>
1415 <para>See also <xref linkend="hasktags" />.</para>
1421 <literal>:type</literal> <replaceable>expression</replaceable>
1422 <indexterm><primary><literal>:type</literal></primary></indexterm>
1425 <para>Infers and prints the type of
1426 <replaceable>expression</replaceable>, including explicit
1427 forall quantifiers for polymorphic types. The monomorphism
1428 restriction is <emphasis>not</emphasis> applied to the
1429 expression during type inference.</para>
1435 <literal>:kind</literal> <replaceable>type</replaceable>
1436 <indexterm><primary><literal>:kind</literal></primary></indexterm>
1439 <para>Infers and prints the kind of
1440 <replaceable>type</replaceable>. The latter can be an arbitrary
1441 type expression, including a partial application of a type constructor,
1442 such as <literal>Either Int</literal>.</para>
1448 <literal>:undef</literal> <replaceable>name</replaceable>
1449 <indexterm><primary><literal>:undef</literal></primary></indexterm>
1452 <para>Undefines the user-defined command
1453 <replaceable>name</replaceable> (see <literal>:def</literal>
1460 <literal>:unset</literal> <replaceable>option</replaceable>...
1461 <indexterm><primary><literal>:unset</literal></primary></indexterm>
1464 <para>Unsets certain options. See <xref linkend="ghci-set"/>
1465 for a list of available options.</para>
1471 <literal>:!</literal> <replaceable>command</replaceable>...
1472 <indexterm><primary><literal>:!</literal></primary></indexterm>
1473 <indexterm><primary>shell commands</primary><secondary>in GHCi</secondary></indexterm>
1476 <para>Executes the shell command
1477 <replaceable>command</replaceable>.</para>
1484 <sect1 id="ghci-set">
1485 <title>The <literal>:set</literal> command</title>
1486 <indexterm><primary><literal>:set</literal></primary></indexterm>
1488 <para>The <literal>:set</literal> command sets two types of
1489 options: GHCi options, which begin with
1490 ‘<literal>+</literal>” and “command-line”
1491 options, which begin with ‘-’. </para>
1493 <para>NOTE: at the moment, the <literal>:set</literal> command
1494 doesn't support any kind of quoting in its arguments: quotes will
1495 not be removed and cannot be used to group words together. For
1496 example, <literal>:set -DFOO='BAR BAZ'</literal> will not do what
1500 <title>GHCi options</title>
1501 <indexterm><primary>options</primary><secondary>GHCi</secondary>
1504 <para>GHCi options may be set using <literal>:set</literal> and
1505 unset using <literal>:unset</literal>.</para>
1507 <para>The available GHCi options are:</para>
1512 <literal>+r</literal>
1513 <indexterm><primary><literal>+r</literal></primary></indexterm>
1514 <indexterm><primary>CAFs</primary><secondary>in GHCi</secondary></indexterm>
1515 <indexterm><primary>Constant Applicative Form</primary><see>CAFs</see></indexterm>
1518 <para>Normally, any evaluation of top-level expressions
1519 (otherwise known as CAFs or Constant Applicative Forms) in
1520 loaded modules is retained between evaluations. Turning
1521 on <literal>+r</literal> causes all evaluation of
1522 top-level expressions to be discarded after each
1523 evaluation (they are still retained
1524 <emphasis>during</emphasis> a single evaluation).</para>
1526 <para>This option may help if the evaluated top-level
1527 expressions are consuming large amounts of space, or if
1528 you need repeatable performance measurements.</para>
1534 <literal>+s</literal>
1535 <indexterm><primary><literal>+s</literal></primary></indexterm>
1538 <para>Display some stats after evaluating each expression,
1539 including the elapsed time and number of bytes allocated.
1540 NOTE: the allocation figure is only accurate to the size
1541 of the storage manager's allocation area, because it is
1542 calculated at every GC. Hence, you might see values of
1543 zero if no GC has occurred.</para>
1549 <literal>+t</literal>
1550 <indexterm><primary><literal>+t</literal></primary></indexterm>
1553 <para>Display the type of each variable bound after a
1554 statement is entered at the prompt. If the statement is a
1555 single expression, then the only variable binding will be
1557 ‘<literal>it</literal>’.</para>
1563 <sect2 id="ghci-cmd-line-options">
1564 <title>Setting GHC command-line options in GHCi</title>
1566 <para>Normal GHC command-line options may also be set using
1567 <literal>:set</literal>. For example, to turn on
1568 <option>-fglasgow-exts</option>, you would say:</para>
1571 Prelude> :set -fglasgow-exts
1574 <para>Any GHC command-line option that is designated as
1575 <firstterm>dynamic</firstterm> (see the table in <xref
1576 linkend="flag-reference"/>), may be set using
1577 <literal>:set</literal>. To unset an option, you can set the
1578 reverse option:</para>
1579 <indexterm><primary>dynamic</primary><secondary>options</secondary></indexterm>
1582 Prelude> :set -fno-glasgow-exts
1585 <para><xref linkend="flag-reference"/> lists the reverse for each
1586 option where applicable.</para>
1588 <para>Certain static options (<option>-package</option>,
1589 <option>-I</option>, <option>-i</option>, and
1590 <option>-l</option> in particular) will also work, but some may
1591 not take effect until the next reload.</para>
1592 <indexterm><primary>static</primary><secondary>options</secondary></indexterm>
1595 <sect1 id="ghci-debugger">
1596 <title>The GHCi debugger</title>
1597 <indexterm><primary>debugger</primary></indexterm>
1598 <para>GHCi embeds an utility debugger with a very basic set of operations. The debugger
1599 is always available in ghci, you do not need to do anything to activate it. </para>
1600 <para>The following conditions must hold before a module can be debugged in GHCi:
1603 <para>The module must have been loaded interpreted, i.e. not loaded from an <filename>.o</filename> file compiled by ghc </para>
1605 </itemizedlist></para>
1606 <sect2><title>Using the debugger</title>
1607 <para>The debugger allows the insertion of breakpoints at specific locations in the source code. These locations are governed by event sites, and not by line as in traditional debuggers such as gdb. </para> <para>
1608 Once a breakpointed event is hit, the debugger stops the execution and you can examine the local variables in scope
1609 in the context of the event, as well as evaluate arbitrary Haskell expressions in
1610 a special interactive prompt. </para><para>
1612 When you are done you issue the <literal>:continue</literal>
1613 command to leave the breakpoint and let the execution go on.
1614 Note that not all the GHCi commands are supported in a breakpoint.
1617 <sidebar><title>Events</title><?dbfo float-type="left"?>
1618 <para> Events are the places in source code where you can set a breakpoint.
1620 qsort [] = <co id="name-binding-co"/> []
1622 <coref linkend="name-binding-co"/> let left = <coref linkend="name-binding-co"/> filter (\y -> <co id="lambda-co"/> y < x) xs
1623 right = <coref linkend="name-binding-co"/> case filter (\y -> <coref linkend="lambda-co"/> y > x) xs of
1624 right_val -> <co id="case-co"/> right_val
1625 in <co id="let-co"/> qsort left ++ [x] ++ qsort right
1626 main = <coref linkend="name-binding-co"/> do {
1627 arg <- <coref linkend="name-binding-co"/> getLine ;
1628 let num = <coref linkend="name-binding-co"/> read arg :: [Int] ;
1629 <co id="stmts-co"/> print (qsort num) ;
1630 <coref linkend="stmts-co"/> putStrLn "GoodBye!" }
1632 The GHCi debugger recognizes the following event types:
1634 <callout arearefs="name-binding-co" id="name-binding">
1635 <para>Function definition and local bindings in let/where</para>
1637 <callout arearefs="lambda-co" id="lambda">
1638 <para>Lambda expression entry point</para>
1640 <callout arearefs="let-co" id="let">
1641 <para>Let expression body</para>
1643 <callout arearefs="case-co" id="case">
1644 <para>Case alternative body</para>
1646 <callout arearefs="stmts-co" id="stmts">
1647 <para>do notation statements</para>
1649 </calloutlist></para>
1650 <para>In reality however, ghci eliminates some redundant event sites.
1651 For instance, sites with two co-located breakpoint events are coalesced into a single one,
1652 and sites with no bindings in scope are assumed to be uninteresting and no breakpoint can be set in them.</para>
1656 You don't need to do anything special in order to start the debugging session.
1657 Simply use ghci to evaluate your Haskell expressions and whenever a breakpoint
1658 is hit, the debugger will enter the stage:
1660 *main:Main> :break qsort
1661 Breakpoint 0 activated at ../QSort.hs:(4,0)-(6,54)
1662 *QSort> qsort [10,9,1]
1663 Stopped at ../QSort.hs:(4,0)-(6,54)
1669 [../QSort.hs:(4,0)-(6,54)] *QSort>
1671 What is happening here is that GHCi has interrupted the evaluation of
1672 <literal>qsort</literal> at the breakpoint, as the prompt indicates.
1673 At this point you can freely explore the contents of the bindings in scope,
1674 but with two catches. </para><para>
1675 First, take into account that due to the lazy nature of Haskell, some of
1676 these bindings may be unevaluated, and that exploring their contents may
1677 trigger a computation. </para><para>
1678 Second: look at the types of the things in scope.
1679 GHCi has left its types parameterised by a variable!
1680 Look at the type of <literal>qsort</literal>, which is
1681 polymorphic on the type of its argument. It does not
1682 tell us really what the types of <literal>x</literal>
1683 and <literal>xs</literal> can be.
1684 In general, polymorphic functions deal with polymorphic values,
1685 and this means that some of the bindings available in a breakpoint site
1686 will be parametrically typed.
1688 So, what can we do with a value without concrete type? Very few interesting
1689 things, not even using <literal>show</literal> on it.
1690 The <literal>:print</literal> command in ghci allows you to
1691 explore its contents and see if it is evaluated or not.
1692 <literal>:print</literal> works here because it does not need the
1693 type information to do its work. In fact, as we will see later,
1694 <literal>:print</literal> can even recover the missing type information.</para>
1696 <para> Let's go on with the debugging session of the <literal>qsort</literal>
1698 <example id="debuggingEx"><title>A short debugging session</title>
1700 qsort2.hs:2:15-46> x
1701 <interactive>:1:0:
1702 Ambiguous type variable `a' in the constraint: <co id="seq1"/>
1703 `Show a' arising from a use of `print' at <interactive>:1:0
1704 qsort2.hs:2:15-46> seq x () <co id="seq2"/>
1706 qsort2.hs:2:15-46> x <co id="seq3"/>
1707 <interactive>:1:0:
1708 Ambiguous type variable `a' in the constraint:
1709 `Show a' arising from a use of `print' at <interactive>:1:0
1710 qsort2.hs:2:15-46> :t x
1712 qsort2.hs:2:15-46> :print x <co id="seq4"/>
1714 qsort2.hs:2:15-46> :t x <co id="seq5"/>
1719 <callout arearefs="seq1">
1720 <para>GHCi reminds us that <literal>x</literal> is untyped </para>
1722 <callout arearefs="seq2">
1723 <para>This line forces the evaluation of <literal>x</literal> </para>
1725 <callout arearefs="seq3">
1726 <para>Even though x has been evaluated,
1727 we have not updated its type yet. </para>
1729 <callout arearefs="seq4">
1730 <para>We can explore <literal>x</literal> using the <literal>:print</literal>
1731 command, which does find out that <literal>x</literal> is of type Int and
1732 prints its value.</para>
1734 <callout arearefs="seq5">
1735 <para>In addition, <literal>:print</literal> also updates
1736 its type information.</para>
1740 This example shows the standard way to proceeed with polymorphic values in a breakpoint.
1743 <sect2><title>Commands</title>
1744 <para>Breakpoints can be set in several ways using the <literal>:breakpoint</literal> command. Note that you can take advantage of the command abbreviation feature of GHCi and use simply <literal>:bre</literal> to save quite a few keystrokes.
1748 <literal>:breakpoint add <replaceable>module</replaceable> <replaceable>line</replaceable></literal>
1751 Adds a breakpoint at the first event found at line <literal>line</literal> in <literal>module</literal>, if any.
1756 <literal>:breakpoint add <replaceable>module</replaceable> <replaceable>line</replaceable> <replaceable>column</replaceable></literal>
1759 Adds a breakpoint at the first event found after column <literal>column</literal>
1760 at line <literal>line</literal> in <literal>module</literal>, if any.
1766 <literal>:breakpoint continue</literal>
1769 When at a breakpoint, continue execution up to the next breakpoint
1770 or end of evaluation.
1776 <literal>:continue</literal>
1779 Shortcut for <literal>:breakpoint continue</literal>
1785 <literal>:breakpoint list</literal>
1788 Lists the currently set up breakpoints.
1793 <literal>:breakpoint del <replaceable>num</replaceable></literal>
1796 Deletes the breakpoint at position <literal>num</literal> in the list of
1797 breakpoints shown by <literal>:breakpoint list</literal>.
1802 <literal>:breakpoint del <replaceable>module</replaceable> <replaceable>line</replaceable></literal>
1805 Dels the breakpoint at line <literal>line</literal> in <literal>module</literal>, if any.
1810 <literal>:breakpoint del <replaceable>module</replaceable> <replaceable>line</replaceable><replaceable>col</replaceable> </literal>
1813 Deletes the first breakpoint found after column <literal>column</literal>
1814 at line <literal>line</literal> in <literal>module</literal>, if any.
1819 <literal>:breakpoint stop </literal>
1822 Stop the program being executed. This interrupts a debugging session
1823 and returns to the top level.
1826 </variablelist></para>
1828 <sect2><title>Debugging Higher-Order functions</title>
1830 It is possible to use the debugger to examine lambdas.
1831 When we are at a breakpoint and a lambda is in scope, the debugger cannot show
1832 you the source code that constitutes it; however, it is possible to get some
1833 information by applying it to some arguments and observing the result.
1835 The process is slightly complicated when the binding is polymorphic.
1836 We show the process by means of an example.
1837 To keep things simple, we will use the well known <literal>map</literal> function:
1839 import Prelude hiding (map)
1841 map :: (a->b) -> a -> b
1843 map f (x:xs) = f x : map f xs
1846 We set a breakpoint on <literal>map</literal>, and call it.
1849 Breakpoint 0 activated at map.hs:(4,0)-(5,12)
1850 *Main> map Just [1..5]
1851 Stopped at map.hs:(4,0)-(5,12)
1857 GHCi tells us that, among other bindings, <literal>f</literal> is in scope.
1858 However, its type is not fully known yet,
1859 and thus it is not possible to apply it to any
1860 arguments. Nevertheless, observe that the type of its first argument is the
1861 same as the type of <literal>x</literal>, and its result type is the
1862 same as the type of <literal>_result</literal>.
1864 The debugger has some intelligence built-in to update the type of
1865 <literal>f</literal> whenever the types of <literal>x</literal> or
1866 <literal>_result</literal> are reconstructed. So what we do in this scenario is
1867 force <literal>x</literal> a bit, in order to recover both its type
1868 and the argument part of <literal>f</literal>.
1875 We can check now that as expected, the type of <literal>x</literal>
1876 has been reconstructed, and with it the
1877 type of <literal>f</literal> has been too:
1885 From here, we can apply f to any argument of type Integer and observe the
1887 <programlisting><![CDATA[
1893 Ambiguous type variable `b' in the constraint:
1894 `Show b' arising from a use of `print' at <interactive>:1:0
1906 f :: Integer -> Maybe Integer
1910 [Just 1, Just 2, Just 3, Just 4, Just 5]
1911 ]]></programlisting>
1912 In the first application of <literal>f</literal>, we had to do
1913 some more type reconstruction
1914 in order to recover the result type of <literal>f</literal>.
1915 But after that, we are free to use
1916 <literal>f</literal> normally.
1919 <sect2><title>Tips</title>
1921 <varlistentry> <term>* Repeated use of <literal>seq</literal> and
1922 <literal>:print</literal> may be necessary to observe unevaluated
1923 untyped bindings</term>
1924 <listitem><para>see <xref linkend="debuggingEx"/>
1927 <varlistentry> <term> * <literal>GHC.Exts.unsafeCoerce</literal> can help if you are positive about the type of a binding</term>
1928 <listitem><para><programlisting>
1929 type MyLongType a = [Maybe [Maybe a]]
1933 Local bindings in scope:
1935 Main.hs:15> let x' = unsafeCoerce x :: MyLongType Bool
1937 [Just [Just False, Just True]]
1939 Note that a wrong coercion will likely result in your debugging session being interrupted by a segmentation fault
1942 <varlistentry> <term> * The <literal>:force</literal> command </term>
1944 equivalent to <literal> :print</literal> with automatic
1945 <literal>seq</literal> forcing,
1946 may prove useful to replace sequences of <literal>seq</literal> and
1947 <literal>:print</literal> in some situations.
1952 <sect2><title>Limitations</title>
1956 Implicit parameters (see <xref linkend="implicit-parameters"/>) are only available
1957 at the scope of a breakpoint if there is a explicit type signature.
1963 <sect1 id="ghci-dot-files">
1964 <title>The <filename>.ghci</filename> file</title>
1965 <indexterm><primary><filename>.ghci</filename></primary><secondary>file</secondary>
1967 <indexterm><primary>startup</primary><secondary>files, GHCi</secondary>
1970 <para>When it starts, GHCi always reads and executes commands from
1971 <filename>$HOME/.ghci</filename>, followed by
1972 <filename>./.ghci</filename>.</para>
1974 <para>The <filename>.ghci</filename> in your home directory is
1975 most useful for turning on favourite options (eg. <literal>:set
1976 +s</literal>), and defining useful macros. Placing a
1977 <filename>.ghci</filename> file in a directory with a Haskell
1978 project is a useful way to set certain project-wide options so you
1979 don't have to type them everytime you start GHCi: eg. if your
1980 project uses GHC extensions and CPP, and has source files in three
1981 subdirectories A B and C, you might put the following lines in
1982 <filename>.ghci</filename>:</para>
1985 :set -fglasgow-exts -cpp
1989 <para>(Note that strictly speaking the <option>-i</option> flag is
1990 a static one, but in fact it works to set it using
1991 <literal>:set</literal> like this. The changes won't take effect
1992 until the next <literal>:load</literal>, though.)</para>
1994 <para>Two command-line options control whether the
1995 <filename>.ghci</filename> files are read:</para>
2000 <option>-ignore-dot-ghci</option>
2001 <indexterm><primary><option>-ignore-dot-ghci</option></primary></indexterm>
2004 <para>Don't read either <filename>./.ghci</filename> or
2005 <filename>$HOME/.ghci</filename> when starting up.</para>
2010 <option>-read-dot-ghci</option>
2011 <indexterm><primary><option>-read-dot-ghci</option></primary></indexterm>
2014 <para>Read <filename>.ghci</filename> and
2015 <filename>$HOME/.ghci</filename>. This is normally the
2016 default, but the <option>-read-dot-ghci</option> option may
2017 be used to override a previous
2018 <option>-ignore-dot-ghci</option> option.</para>
2025 <sect1 id="ghci-obj">
2026 <title>Compiling to object code inside GHCi</title>
2028 <para>By default, GHCi compiles Haskell source code into byte-code
2029 that is interpreted by the runtime system. GHCi can also compile
2030 Haskell code to object code: to turn on this feature, use the
2031 <option>-fobject-code</option> flag either on the command line or
2032 with <literal>:set</literal> (the option
2033 <option>-fbyte-code</option> restores byte-code compilation
2034 again). Compiling to object code takes longer, but typically the
2035 code will execute 10-20 times faster than byte-code.</para>
2037 <para>Compiling to object code inside GHCi is particularly useful
2038 if you are developing a compiled application, because the
2039 <literal>:reload</literal> command typically runs much faster than
2040 restarting GHC with <option>--make</option> from the command-line,
2041 because all the interface files are already cached in
2044 <para>There are disadvantages to compiling to object-code: you
2045 can't set breakpoints in object-code modules, for example. Only
2046 the exports of an object-code module will be visible in GHCi,
2047 rather than all top-level bindings as in interpreted
2051 <sect1 id="ghci-faq">
2052 <title>FAQ and Things To Watch Out For</title>
2056 <term>The interpreter can't load modules with foreign export
2057 declarations!</term>
2059 <para>Unfortunately not. We haven't implemented it yet.
2060 Please compile any offending modules by hand before loading
2061 them into GHCi.</para>
2067 <literal>-O</literal> doesn't work with GHCi!
2068 <indexterm><primary><option>-O</option></primary></indexterm>
2071 <para>For technical reasons, the bytecode compiler doesn't
2072 interact well with one of the optimisation passes, so we
2073 have disabled optimisation when using the interpreter. This
2074 isn't a great loss: you'll get a much bigger win by
2075 compiling the bits of your code that need to go fast, rather
2076 than interpreting them with optimisation turned on.</para>
2081 <term>Unboxed tuples don't work with GHCi</term>
2083 <para>That's right. You can always compile a module that
2084 uses unboxed tuples and load it into GHCi, however.
2085 (Incidentally the previous point, namely that
2086 <literal>-O</literal> is incompatible with GHCi, is because
2087 the bytecode compiler can't deal with unboxed
2093 <term>Concurrent threads don't carry on running when GHCi is
2094 waiting for input.</term>
2096 <para>This should work, as long as your GHCi was built with
2097 the <option>-threaded</option> switch, which is the default.
2098 Consult whoever supplied your GHCi installation.</para>
2103 <term>After using <literal>getContents</literal>, I can't use
2104 <literal>stdin</literal> again until I do
2105 <literal>:load</literal> or <literal>:reload</literal>.</term>
2108 <para>This is the defined behaviour of
2109 <literal>getContents</literal>: it puts the stdin Handle in
2110 a state known as <firstterm>semi-closed</firstterm>, wherein
2111 any further I/O operations on it are forbidden. Because I/O
2112 state is retained between computations, the semi-closed
2113 state persists until the next <literal>:load</literal> or
2114 <literal>:reload</literal> command.</para>
2116 <para>You can make <literal>stdin</literal> reset itself
2117 after every evaluation by giving GHCi the command
2118 <literal>:set +r</literal>. This works because
2119 <literal>stdin</literal> is just a top-level expression that
2120 can be reverted to its unevaluated state in the same way as
2121 any other top-level expression (CAF).</para>
2126 <term>I can't use Control-C to interrupt computations in
2127 GHCi on Windows.</term>
2129 <para>See <xref linkend="ghci-windows"/></para>
2138 ;;; Local Variables: ***
2140 ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") ***