#1205: ':load foo.hs' in GHCi always compiles to bytecode
[ghc-hetmet.git] / docs / users_guide / ghci.xml
1 <?xml version="1.0" encoding="iso-8859-1"?>
2 <chapter id="ghci">
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>
7   
8   <para>GHCi<footnote>
9       <para>The &lsquo;i&rsquo; stands for &ldquo;Interactive&rdquo;</para>
10     </footnote>
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.
18   <indexterm><primary>FFI</primary><secondary>GHCi support</secondary></indexterm>
19   <indexterm><primary>Foreign Function
20   Interface</primary><secondary>GHCi support</secondary></indexterm>.
21   GHCi also includes an interactive debugger (see <xref linkend="ghci-debugger"/>).</para>
22
23   <sect1 id="ghci-introduction">
24     <title>Introduction to GHCi</title>
25
26     <para>Let's start with an example GHCi session.  You can fire up
27     GHCi with the command <literal>ghci</literal>:</para>
28
29 <screen>
30 $ ghci
31 GHCi, version 6.8.1: http://www.haskell.org/ghc/  :? for help
32 Loading package base ... linking ... done.
33 Prelude> 
34 </screen>
35
36     <para>There may be a short pause while GHCi loads the prelude and
37     standard libraries, after which the prompt is shown. As the banner
38     says, you can type <literal>:?</literal> to see the list of commands
39     available, and a half line description of each of them.</para>
40
41     <para>We'll explain most of these commands as we go along.  For
42     Hugs users: many things work the same as in Hugs, so you should be
43     able to get going straight away.</para>
44
45     <para>Haskell expressions can be typed at the prompt:</para>
46     <indexterm><primary>prompt</primary><secondary>GHCi</secondary>
47   </indexterm>
48
49 <screen>
50 Prelude> 1+2
51 3
52 Prelude> let x = 42 in x / 9
53 4.666666666666667
54 Prelude> 
55 </screen>
56
57     <para>GHCi interprets the whole line as an expression to evaluate.
58     The expression may not span several lines - as soon as you press
59     enter, GHCi will attempt to evaluate it.</para>
60   </sect1>
61
62   <sect1 id="loading-source-files">
63     <title>Loading source files</title>
64
65     <para>Suppose we have the following Haskell source code, which we
66     place in a file <filename>Main.hs</filename>:</para>
67
68 <programlisting>
69 main = print (fac 20)
70
71 fac 0 = 1
72 fac n = n * fac (n-1)
73 </programlisting>
74
75     <para>You can save <filename>Main.hs</filename> anywhere you like,
76     but if you save it somewhere other than the current
77     directory<footnote><para>If you started up GHCi from the command
78     line then GHCi's current directory is the same as the current
79     directory of the shell from which it was started.  If you started
80     GHCi from the &ldquo;Start&rdquo; menu in Windows, then the
81     current directory is probably something like
82     <filename>C:\Documents and Settings\<replaceable>user
83     name</replaceable></filename>.</para> </footnote> then we will
84     need to change to the right directory in GHCi:</para>
85
86 <screen>
87 Prelude> :cd <replaceable>dir</replaceable>
88 </screen>
89
90     <para>where <replaceable>dir</replaceable> is the directory (or
91     folder) in which you saved <filename>Main.hs</filename>.</para>
92
93     <para>To load a Haskell source file into GHCi, use the
94     <literal>:load</literal> command:</para>
95     <indexterm><primary><literal>:load</literal></primary></indexterm>
96
97 <screen>
98 Prelude> :load Main
99 Compiling Main             ( Main.hs, interpreted )
100 Ok, modules loaded: Main.
101 *Main>
102 </screen>
103
104     <para>GHCi has loaded the <literal>Main</literal> module, and the
105     prompt has changed to &ldquo;<literal>*Main></literal>&rdquo; to
106     indicate that the current context for expressions typed at the
107     prompt is the <literal>Main</literal> module we just loaded (we'll
108     explain what the <literal>*</literal> means later in <xref
109     linkend="ghci-scope"/>).  So we can now type expressions involving
110     the functions from <filename>Main.hs</filename>:</para>
111
112 <screen>
113 *Main> fac 17
114 355687428096000
115 </screen>
116
117     <para>Loading a multi-module program is just as straightforward;
118     just give the name of the &ldquo;topmost&rdquo; module to the
119     <literal>:load</literal> command (hint: <literal>:load</literal>
120     can be abbreviated to <literal>:l</literal>).  The topmost module
121     will normally be <literal>Main</literal>, but it doesn't have to
122     be.  GHCi will discover which modules are required, directly or
123     indirectly, by the topmost module, and load them all in dependency
124     order.</para>
125
126     <sect2 id="ghci-modules-filenames">
127       <title>Modules vs. filenames</title>
128       <indexterm><primary>modules</primary><secondary>and filenames</secondary></indexterm>
129       <indexterm><primary>filenames</primary><secondary>of modules</secondary></indexterm>
130       
131       <para>Question: How does GHC find the filename which contains
132       module <replaceable>M</replaceable>?  Answer: it looks for the
133       file <literal><replaceable>M</replaceable>.hs</literal>, or
134       <literal><replaceable>M</replaceable>.lhs</literal>.  This means
135       that for most modules, the module name must match the filename.
136       If it doesn't, GHCi won't be able to find it.</para>
137
138       <para>There is one exception to this general rule: when you load
139       a program with <literal>:load</literal>, or specify it when you
140       invoke <literal>ghci</literal>, you can give a filename rather
141       than a module name.  This filename is loaded if it exists, and
142       it may contain any module you like.  This is particularly
143       convenient if you have several <literal>Main</literal> modules
144       in the same directory and you can't call them all
145       <filename>Main.hs</filename>.</para>
146
147       <para>The search path for finding source files is specified with
148       the <option>-i</option> option on the GHCi command line, like
149       so:</para>
150 <screen>ghci -i<replaceable>dir<subscript>1</subscript></replaceable>:...:<replaceable>dir<subscript>n</subscript></replaceable></screen>
151
152       <para>or it can be set using the <literal>:set</literal> command
153       from within GHCi (see <xref
154       linkend="ghci-cmd-line-options"/>)<footnote><para>Note that in
155       GHCi, and <option>&ndash;&ndash;make</option> mode, the <option>-i</option>
156       option is used to specify the search path for
157       <emphasis>source</emphasis> files, whereas in standard
158       batch-compilation mode the <option>-i</option> option is used to
159       specify the search path for interface files, see <xref
160       linkend="search-path"/>.</para> </footnote></para>
161
162       <para>One consequence of the way that GHCi follows dependencies
163       to find modules to load is that every module must have a source
164       file.  The only exception to the rule is modules that come from
165       a package, including the <literal>Prelude</literal> and standard
166       libraries such as <literal>IO</literal> and
167       <literal>Complex</literal>.  If you attempt to load a module for
168       which GHCi can't find a source file, even if there are object
169       and interface files for the module, you'll get an error
170       message.</para>
171     </sect2>
172
173     <sect2>
174       <title>Making changes and recompilation</title>
175       <indexterm><primary><literal>:reload</literal></primary></indexterm>
176
177       <para>If you make some changes to the source code and want GHCi
178       to recompile the program, give the <literal>:reload</literal>
179       command.  The program will be recompiled as necessary, with GHCi
180       doing its best to avoid actually recompiling modules if their
181       external dependencies haven't changed.  This is the same
182       mechanism we use to avoid re-compiling modules in the batch
183       compilation setting (see <xref linkend="recomp"/>).</para>
184     </sect2>
185   </sect1>
186
187   <sect1 id="ghci-compiled">
188     <title>Loading compiled code</title>
189     <indexterm><primary>compiled code</primary><secondary>in GHCi</secondary></indexterm>
190
191     <para>When you load a Haskell source module into GHCi, it is
192     normally converted to byte-code and run using the interpreter.
193     However, interpreted code can also run alongside compiled code in
194     GHCi; indeed, normally when GHCi starts, it loads up a compiled
195     copy of the <literal>base</literal> package, which contains the
196     <literal>Prelude</literal>.</para>
197
198     <para>Why should we want to run compiled code?  Well, compiled
199     code is roughly 10x faster than interpreted code, but takes about
200     2x longer to produce (perhaps longer if optimisation is on).  So
201     it pays to compile the parts of a program that aren't changing
202     very often, and use the interpreter for the code being actively
203     developed.</para>
204
205     <para>When loading up source modules with <literal>:load</literal>,
206     GHCi normally looks for any corresponding compiled object files,
207     and will use one in preference to interpreting the source if
208     possible.  For example, suppose we have a 4-module program
209     consisting of modules A, B, C, and D.  Modules B and C both import
210     D only, and A imports both B &amp; C:</para>
211 <screen>
212       A
213      / \
214     B   C
215      \ /
216       D
217 </screen>
218     <para>We can compile D, then load the whole program, like this:</para>
219 <screen>
220 Prelude> :! ghc -c D.hs
221 Prelude> :load A
222 Compiling B                ( B.hs, interpreted )
223 Compiling C                ( C.hs, interpreted )
224 Compiling A                ( A.hs, interpreted )
225 Ok, modules loaded: A, B, C, D.
226 *Main>
227 </screen>
228
229     <para>In the messages from the compiler, we see that there is no line
230     for <literal>D</literal>. This is because
231     it isn't necessary to compile <literal>D</literal>,
232     because the source and everything it depends on
233     is unchanged since the last compilation.</para>
234
235     <para>At any time you can use the command 
236     <literal>:show modules</literal>
237     to get a list of the modules currently loaded
238     into GHCi:</para>
239
240 <screen>
241 *Main> :show modules
242 D                ( D.hs, D.o )
243 C                ( C.hs, interpreted )
244 B                ( B.hs, interpreted )
245 A                ( A.hs, interpreted )
246 *Main></screen>
247
248     <para>If we now modify the source of D (or pretend to: using the Unix
249     command <literal>touch</literal> on the source file is handy for
250     this), the compiler will no longer be able to use the object file,
251     because it might be out of date:</para>
252
253 <screen>
254 *Main> :! touch D.hs
255 *Main> :reload
256 Compiling D                ( D.hs, interpreted )
257 Ok, modules loaded: A, B, C, D.
258 *Main> 
259 </screen>
260
261     <para>Note that module D was compiled, but in this instance
262     because its source hadn't really changed, its interface remained
263     the same, and the recompilation checker determined that A, B and C
264     didn't need to be recompiled.</para>
265
266     <para>So let's try compiling one of the other modules:</para>
267
268 <screen>
269 *Main> :! ghc -c C.hs
270 *Main> :load A
271 Compiling D                ( D.hs, interpreted )
272 Compiling B                ( B.hs, interpreted )
273 Compiling C                ( C.hs, interpreted )
274 Compiling A                ( A.hs, interpreted )
275 Ok, modules loaded: A, B, C, D.
276 </screen>
277
278     <para>We didn't get the compiled version of C!  What happened?
279     Well, in GHCi a compiled module may only depend on other compiled
280     modules, and in this case C depends on D, which doesn't have an
281     object file, so GHCi also rejected C's object file.  Ok, so let's
282     also compile D:</para>
283
284 <screen>
285 *Main> :! ghc -c D.hs
286 *Main> :reload
287 Ok, modules loaded: A, B, C, D.
288 </screen>
289
290     <para>Nothing happened!  Here's another lesson: newly compiled
291     modules aren't picked up by <literal>:reload</literal>, only
292     <literal>:load</literal>:</para>
293
294 <screen>
295 *Main> :load A
296 Compiling B                ( B.hs, interpreted )
297 Compiling A                ( A.hs, interpreted )
298 Ok, modules loaded: A, B, C, D.
299 </screen>
300
301     <para>The automatic loading of object files can sometimes lead to
302     confusion, because non-exported top-level definitions of a module
303     are only available for use in expressions at the prompt when the
304     module is interpreted (see <xref linkend="ghci-scope" />).  For
305     this reason, if you ask GHCi to load a filename rather than a
306     module name (e.g. <literal>:load Main.hs</literal> rather than
307     <literal>:load Main</literal>) then any existing object file will
308     be ignored and the module will be interpreted rather than
309     compiled.  Using <literal>-fobject-code</literal> disables this
310     behaviour (see <xref linkend="ghci-obj" />).</para>
311
312     <para>HINT: since GHCi will only use a compiled object file if it
313     can be sure that the compiled version is up-to-date, a good technique
314     when working on a large program is to occasionally run
315     <literal>ghc &ndash;&ndash;make</literal> to compile the whole project (say
316     before you go for lunch :-), then continue working in the
317     interpreter.  As you modify code, the changed modules will be
318     interpreted, but the rest of the project will remain
319     compiled.</para>
320   </sect1>
321
322   <sect1 id="interactive-evaluation">
323     <title>Interactive evaluation at the prompt</title>
324
325     <para>When you type an expression at the prompt, GHCi immediately
326     evaluates and prints the result:
327 <screen>
328 Prelude> reverse "hello"
329 "olleh"
330 Prelude> 5+5
331 10
332 </screen>
333 </para>
334
335 <sect2><title>I/O actions at the prompt</title>
336
337 <para>GHCi does more than simple expression evaluation at the prompt.
338 If you type something of type <literal>IO a</literal> for some
339     <literal>a</literal>, then GHCi <emphasis>executes</emphasis> it
340     as an IO-computation.
341 <screen>
342 Prelude> "hello"
343 "hello"
344 Prelude> putStrLn "hello"
345 hello
346 </screen>
347 Furthermore, GHCi will print the result of the I/O action if (and only
348 if):
349 <itemizedlist>
350   <listitem><para>The result type is an instance of <literal>Show</literal>.</para></listitem>
351   <listitem><para>The result type is not
352   <literal>()</literal>.</para></listitem>
353 </itemizedlist>
354 For example, remembering that <literal>putStrLn :: String -> IO ()</literal>:
355 <screen>
356 Prelude> putStrLn "hello"
357 hello
358 Prelude> do { putStrLn "hello"; return "yes" }
359 hello
360 "yes"
361 </screen>
362 </para></sect2>
363
364     <sect2 id="ghci-stmts">
365       <title>Using <literal>do-</literal>notation at the prompt</title>
366       <indexterm><primary>do-notation</primary><secondary>in GHCi</secondary></indexterm>
367       <indexterm><primary>statements</primary><secondary>in GHCi</secondary></indexterm>
368       
369       <para>GHCi actually accepts <firstterm>statements</firstterm>
370       rather than just expressions at the prompt.  This means you can
371       bind values and functions to names, and use them in future
372       expressions or statements.</para>
373
374       <para>The syntax of a statement accepted at the GHCi prompt is
375       exactly the same as the syntax of a statement in a Haskell
376       <literal>do</literal> expression.  However, there's no monad
377       overloading here: statements typed at the prompt must be in the
378       <literal>IO</literal> monad.
379 <screen>
380 Prelude> x &lt;- return 42
381 Prelude> print x
382 42
383 Prelude>
384 </screen>
385       The statement <literal>x &lt;- return 42</literal> means
386       &ldquo;execute <literal>return 42</literal> in the
387       <literal>IO</literal> monad, and bind the result to
388       <literal>x</literal>&rdquo;.  We can then use
389       <literal>x</literal> in future statements, for example to print
390       it as we did above.</para>
391
392       <para>If <option>-fprint-bind-result</option> is set then
393       GHCi will print the result of a statement if and only if: 
394         <itemizedlist>
395           <listitem>
396             <para>The statement is not a binding, or it is a monadic binding 
397               (<literal>p &lt;- e</literal>) that binds exactly one
398               variable.</para>
399           </listitem>
400           <listitem>
401             <para>The variable's type is not polymorphic, is not
402               <literal>()</literal>, and is an instance of
403               <literal>Show</literal></para>
404           </listitem>
405         </itemizedlist>
406       <indexterm><primary><option>-fprint-bind-result</option></primary></indexterm><indexterm><primary><option>-fno-print-bind-result</option></primary></indexterm>.
407       </para>
408
409       <para>Of course, you can also bind normal non-IO expressions
410       using the <literal>let</literal>-statement:</para>
411 <screen>
412 Prelude> let x = 42
413 Prelude> x
414 42
415 Prelude>
416 </screen>
417       <para>Another important difference between the two types of binding
418       is that the monadic bind (<literal>p &lt;- e</literal>) is
419       <emphasis>strict</emphasis> (it evaluates <literal>e</literal>),
420       whereas with the <literal>let</literal> form, the expression
421       isn't evaluated immediately:</para>
422 <screen>
423 Prelude> let x = error "help!"
424 Prelude> print x
425 *** Exception: help!
426 Prelude>
427 </screen>
428
429       <para>Note that <literal>let</literal> bindings do not automatically
430         print the value bound, unlike monadic bindings.</para>
431
432       <para>Hint: you can also use <literal>let</literal>-statements
433       to define functions at the prompt:</para>
434 <screen>
435 Prelude> let add a b = a + b
436 Prelude> add 1 2
437 3
438 Prelude>
439 </screen>
440         <para>However, this quickly gets tedious when defining functions 
441         with multiple clauses, or groups of mutually recursive functions,
442         because the complete definition has to be given on a single line, 
443         using explicit braces and semicolons instead of layout:</para>
444 <screen>
445 Prelude> let { f op n [] = n ; f op n (h:t) = h `op` f op n t }
446 Prelude> f (+) 0 [1..3]
447 6
448 Prelude>
449 </screen>
450       <para>To alleviate this issue, GHCi commands can be split over
451       multiple lines, by wrapping them in <literal>:{</literal> and
452       <literal>:}</literal> (each on a single line of its own):</para>
453 <screen>
454 Prelude> :{
455 Prelude| let { g op n [] = n
456 Prelude|     ; g op n (h:t) = h `op` g op n t
457 Prelude|     }
458 Prelude| :}
459 Prelude> g (*) 1 [1..3]
460 6
461 </screen>
462       <para>Such multiline commands can be used with any GHCi command,
463       and the lines between <literal>:{</literal> and
464       <literal>:}</literal> are simply merged into a single line for 
465       interpretation. That implies that each such group must form a single
466       valid command when merged, and that no layout rule is used. 
467       The main purpose of multiline commands is not to replace module
468       loading but to make definitions in .ghci-files (see <xref
469       linkend="ghci-dot-files"/>) more readable and maintainable.</para>
470
471       <para>Any exceptions raised during the evaluation or execution
472       of the statement are caught and printed by the GHCi command line
473       interface (for more information on exceptions, see the module
474       <literal>Control.Exception</literal> in the libraries
475       documentation).</para>
476
477       <para>Every new binding shadows any existing bindings of the
478       same name, including entities that are in scope in the current
479       module context.</para>
480
481       <para>WARNING: temporary bindings introduced at the prompt only
482       last until the next <literal>:load</literal> or
483       <literal>:reload</literal> command, at which time they will be
484       simply lost.  However, they do survive a change of context with
485       <literal>:module</literal>: the temporary bindings just move to
486       the new location.</para>
487
488       <para>HINT: To get a list of the bindings currently in scope, use the
489       <literal>:show bindings</literal> command:</para>
490
491 <screen>
492 Prelude> :show bindings
493 x :: Int
494 Prelude></screen>
495
496       <para>HINT: if you turn on the <literal>+t</literal> option,
497       GHCi will show the type of each variable bound by a statement.
498       For example:</para>
499       <indexterm><primary><literal>+t</literal></primary></indexterm>
500 <screen>
501 Prelude> :set +t
502 Prelude> let (x:xs) = [1..]
503 x :: Integer
504 xs :: [Integer]
505 </screen>
506
507     </sect2>
508
509     <sect2 id="ghci-scope">
510       <title>What's really in scope at the prompt?</title> 
511
512       <para>When you type an expression at the prompt, what
513       identifiers and types are in scope?  GHCi provides a flexible
514       way to control exactly how the context for an expression is
515       constructed.  Let's start with the simple cases; when you start
516       GHCi the prompt looks like this:</para>
517
518 <screen>Prelude></screen>
519
520       <para>Which indicates that everything from the module
521       <literal>Prelude</literal> is currently in scope.  If we now
522       load a file into GHCi, the prompt will change:</para>
523
524 <screen>
525 Prelude> :load Main.hs
526 Compiling Main             ( Main.hs, interpreted )
527 *Main>
528 </screen>
529
530       <para>The new prompt is <literal>*Main</literal>, which
531       indicates that we are typing expressions in the context of the
532       top-level of the <literal>Main</literal> module.  Everything
533       that is in scope at the top-level in the module
534       <literal>Main</literal> we just loaded is also in scope at the
535       prompt (probably including <literal>Prelude</literal>, as long
536       as <literal>Main</literal> doesn't explicitly hide it).</para>
537
538       <para>The syntax
539       <literal>*<replaceable>module</replaceable></literal> indicates
540       that it is the full top-level scope of
541       <replaceable>module</replaceable> that is contributing to the
542       scope for expressions typed at the prompt.  Without the
543       <literal>*</literal>, just the exports of the module are
544       visible.</para>
545
546       <para>We're not limited to a single module: GHCi can combine
547       scopes from multiple modules, in any mixture of
548       <literal>*</literal> and non-<literal>*</literal> forms.  GHCi
549       combines the scopes from all of these modules to form the scope
550       that is in effect at the prompt.</para>
551
552       <para>NOTE: for technical reasons, GHCi can only support the
553       <literal>*</literal>-form for modules that are interpreted.
554       Compiled modules and package modules can only contribute their
555       exports to the current scope.  This is why GHCi will always
556       interpret, not compile, a module if you specify its filename
557       rather than its module name to <literal>:load</literal>.</para>
558
559       <para>The scope is manipulated using the
560       <literal>:module</literal> command.  For example, if the current
561       scope is <literal>Prelude</literal>, then we can bring into
562       scope the exports from the module <literal>IO</literal> like
563       so:</para>
564
565 <screen>
566 Prelude> :module +IO
567 Prelude IO> hPutStrLn stdout "hello\n"
568 hello
569 Prelude IO>
570 </screen>
571
572       <para>(Note: you can use <literal>import M</literal> as an
573       alternative to <literal>:module +M</literal>, and
574       <literal>:module</literal> can also be shortened to 
575       <literal>:m</literal>). The full syntax of the
576       <literal>:module</literal> command is:</para>
577
578 <screen>
579 :module <optional>+|-</optional> <optional>*</optional><replaceable>mod<subscript>1</subscript></replaceable> ... <optional>*</optional><replaceable>mod<subscript>n</subscript></replaceable>
580 </screen>
581
582       <para>Using the <literal>+</literal> form of the
583       <literal>module</literal> commands adds modules to the current
584       scope, and <literal>-</literal> removes them.  Without either
585       <literal>+</literal> or <literal>-</literal>, the current scope
586       is replaced by the set of modules specified.  Note that if you
587       use this form and leave out <literal>Prelude</literal>, GHCi
588       will assume that you really wanted the
589       <literal>Prelude</literal> and add it in for you (if you don't
590       want the <literal>Prelude</literal>, then ask to remove it with
591       <literal>:m -Prelude</literal>).</para>
592
593       <para>The scope is automatically set after a
594       <literal>:load</literal> command, to the most recently loaded
595       "target" module, in a <literal>*</literal>-form if possible.
596       For example, if you say <literal>:load foo.hs bar.hs</literal>
597       and <filename>bar.hs</filename> contains module
598       <literal>Bar</literal>, then the scope will be set to
599       <literal>*Bar</literal> if <literal>Bar</literal> is
600       interpreted, or if <literal>Bar</literal> is compiled it will be
601       set to <literal>Prelude Bar</literal> (GHCi automatically adds
602       <literal>Prelude</literal> if it isn't present and there aren't
603       any <literal>*</literal>-form modules).</para>
604
605       <para>With multiple modules in scope, especially multiple
606       <literal>*</literal>-form modules, it is likely that name
607       clashes will occur.  Haskell specifies that name clashes are
608       only reported when an ambiguous identifier is used, and GHCi
609       behaves in the same way for expressions typed at the
610       prompt.</para>
611
612       <para>
613         Hint: GHCi will tab-complete names that are in scope; for
614         example, if you run GHCi and type <literal>J&lt;tab&gt;</literal>
615         then GHCi will expand it to &ldquo;<literal>Just </literal>&rdquo;.
616       </para>
617
618       <sect3>
619         <title>Qualified names</title>
620
621         <para>To make life slightly easier, the GHCi prompt also
622         behaves as if there is an implicit <literal>import
623         qualified</literal> declaration for every module in every
624         package, and every module currently loaded into GHCi.</para>
625       </sect3>
626
627       <sect3>
628         <title>The <literal>:main</literal> and <literal>:run</literal> commands</title>
629
630         <para>
631           When a program is compiled and executed, it can use the
632           <literal>getArgs</literal> function to access the
633           command-line arguments.
634           However, we cannot simply pass the arguments to the
635           <literal>main</literal> function while we are testing in ghci,
636           as the <literal>main</literal> function doesn't take its
637           directly.
638         </para>
639
640         <para>
641           Instead, we can use the <literal>:main</literal> command.
642           This runs whatever <literal>main</literal> is in scope, with
643           any arguments being treated the same as command-line arguments,
644           e.g.:
645         </para>
646
647 <screen>
648 Prelude> let main = System.Environment.getArgs >>= print
649 Prelude> :main foo bar
650 ["foo","bar"]
651 </screen>
652
653         <para>
654             We can also quote arguments which contains characters like
655             spaces, and they are treated like Haskell strings, or we can
656             just use Haskell list syntax:
657         </para>
658
659 <screen>
660 Prelude> :main foo "bar baz"
661 ["foo","bar baz"]
662 Prelude> :main ["foo", "bar baz"]
663 ["foo","bar baz"]
664 </screen>
665
666         <para>
667             Finally, other functions can be called, either with the
668             <literal>-main-is</literal> flag or the <literal>:run</literal>
669             command:
670         </para>
671
672 <screen>
673 Prelude> let foo = putStrLn "foo" >> System.Environment.getArgs >>= print
674 Prelude> let bar = putStrLn "bar" >> System.Environment.getArgs >>= print
675 Prelude> :set -main-is foo
676 Prelude> :main foo "bar baz"
677 foo
678 ["foo","bar baz"]
679 Prelude> :run bar ["foo", "bar baz"]
680 bar
681 ["foo","bar baz"]
682 </screen>
683
684       </sect3>
685     </sect2>
686   
687
688     <sect2>
689       <title>The <literal>it</literal> variable</title>
690       <indexterm><primary><literal>it</literal></primary>
691       </indexterm>
692       
693       <para>Whenever an expression (or a non-binding statement, to be
694       precise) is typed at the prompt, GHCi implicitly binds its value
695       to the variable <literal>it</literal>.  For example:</para>
696 <screen>
697 Prelude> 1+2
698 3
699 Prelude> it * 2
700 6
701 </screen>
702     <para>What actually happens is that GHCi typechecks the
703     expression, and if it doesn't have an <literal>IO</literal> type,
704     then it transforms it as follows: an expression
705     <replaceable>e</replaceable> turns into 
706 <screen>
707 let it = <replaceable>e</replaceable>;
708 print it
709 </screen>
710     which is then run as an IO-action.</para>
711
712     <para>Hence, the original expression must have a type which is an
713     instance of the <literal>Show</literal> class, or GHCi will
714     complain:</para>
715
716 <screen>
717 Prelude&gt; id
718
719 &lt;interactive&gt;:1:0:
720     No instance for (Show (a -&gt; a))
721       arising from use of `print' at &lt;interactive&gt;:1:0-1
722     Possible fix: add an instance declaration for (Show (a -> a))
723     In the expression: print it
724     In a 'do' expression: print it
725 </screen>
726
727     <para>The error message contains some clues as to the
728     transformation happening internally.</para>
729
730       <para>If the expression was instead of type <literal>IO a</literal> for
731       some <literal>a</literal>, then <literal>it</literal> will be
732       bound to the result of the <literal>IO</literal> computation,
733       which is of type <literal>a</literal>.  eg.:</para>
734 <screen>
735 Prelude> Time.getClockTime
736 Wed Mar 14 12:23:13 GMT 2001
737 Prelude> print it
738 Wed Mar 14 12:23:13 GMT 2001
739 </screen>
740
741       <para>The corresponding translation for an IO-typed
742       <replaceable>e</replaceable> is
743 <screen>
744 it &lt;- <replaceable>e</replaceable>
745 </screen>
746       </para>
747
748       <para>Note that <literal>it</literal> is shadowed by the new
749       value each time you evaluate a new expression, and the old value
750       of <literal>it</literal> is lost.</para>
751
752     </sect2>
753
754     <sect2 id="extended-default-rules">
755       <title>Type defaulting in GHCi</title>
756     <indexterm><primary>Type default</primary></indexterm>
757     <indexterm><primary><literal>Show</literal> class</primary></indexterm>
758       <para>
759       Consider this GHCi session:
760 <programlisting>
761   ghci> reverse []
762 </programlisting>
763       What should GHCi do?  Strictly speaking, the program is ambiguous.  <literal>show (reverse [])</literal>
764       (which is what GHCi computes here) has type <literal>Show a => a</literal> and how that displays depends 
765       on the type <literal>a</literal>.  For example:
766 <programlisting>
767   ghci> (reverse []) :: String
768   ""
769   ghci> (reverse []) :: [Int]
770   []
771 </programlisting>
772     However, it is tiresome for the user to have to specify the type, so GHCi extends Haskell's type-defaulting
773     rules (Section 4.3.4 of the Haskell 98 Report (Revised)) as follows.  The
774     standard rules take each group of constraints <literal>(C1 a, C2 a, ..., Cn
775     a)</literal> for each type variable <literal>a</literal>, and defaults the
776     type variable if 
777     <orderedlist>
778         <listitem>
779             <para>
780                 The type variable <literal>a</literal> appears in no
781                 other constraints
782             </para>
783         </listitem>
784         <listitem>
785             <para>
786                 All the classes <literal>Ci</literal> are standard.
787             </para>
788         </listitem>
789         <listitem>
790             <para>
791                 At least one of the classes <literal>Ci</literal> is
792                 numeric.
793             </para>
794         </listitem>
795     </orderedlist>
796     At the GHCi prompt, or with GHC if the
797     <literal>-XExtendedDefaultRules</literal> flag is given,
798     the following additional differences apply:
799     <itemizedlist>
800         <listitem>
801             <para>
802                 Rule 2 above is relaxed thus:
803                 <emphasis>All</emphasis> of the classes
804                 <literal>Ci</literal> are single-parameter type classes.
805             </para>
806         </listitem>
807         <listitem>
808             <para>
809                 Rule 3 above is relaxed this:
810                 At least one of the classes <literal>Ci</literal> is
811                 numeric, <emphasis>or is <literal>Show</literal>,
812                 <literal>Eq</literal>, or
813                 <literal>Ord</literal></emphasis>.
814             </para>
815         </listitem>
816         <listitem>
817             <para>
818                 The unit type <literal>()</literal> is added to the
819                 start of the standard list of types which are tried when
820                 doing type defaulting.
821             </para>
822         </listitem>
823     </itemizedlist>
824     The last point means that, for example, this program:
825 <programlisting>
826 main :: IO ()
827 main = print def
828
829 instance Num ()
830
831 def :: (Num a, Enum a) => a
832 def = toEnum 0
833 </programlisting>
834     prints <literal>()</literal> rather than <literal>0</literal> as the
835     type is defaulted to <literal>()</literal> rather than
836     <literal>Integer</literal>.
837    </para>
838    <para>
839     The motivation for the change is that it means <literal>IO a</literal>
840     actions default to <literal>IO ()</literal>, which in turn means that
841     ghci won't try to print a result when running them. This is
842     particularly important for <literal>printf</literal>, which has an
843     instance that returns <literal>IO a</literal>.
844     However, it is only able to return
845     <literal>undefined</literal>
846     (the reason for the instance having this type is so that printf
847     doesn't require extensions to the class system), so if the type defaults to
848     <literal>Integer</literal> then ghci gives an error when running a
849     printf.
850    </para>
851     </sect2>
852   </sect1>
853
854   <sect1 id="ghci-debugger">
855     <title>The GHCi Debugger</title>
856     <indexterm><primary>debugger</primary><secondary>in GHCi</secondary>
857     </indexterm>
858
859     <para>GHCi contains a simple imperative-style debugger in which you can
860       stop a running computation in order to examine the values of
861       variables.  The debugger is integrated into GHCi, and is turned on by
862       default: no flags are required to enable the debugging
863       facilities.  There is one major restriction: breakpoints and
864       single-stepping are only available in interpreted modules;
865       compiled code is invisible to the debugger<footnote><para>Note that packages
866       only contain compiled code, so debugging a package requires
867       finding its source and loading that directly.</para></footnote>.</para>
868
869     <para>The debugger provides the following:
870     <itemizedlist>
871         <listitem>
872           <para>The ability to set a <firstterm>breakpoint</firstterm> on a
873             function definition or expression in the program.  When the function
874             is called, or the expression evaluated, GHCi suspends 
875             execution and returns to the prompt, where you can inspect the
876             values of local variables before continuing with the
877             execution.</para>
878         </listitem>
879         <listitem>
880           <para>Execution can be <firstterm>single-stepped</firstterm>: the
881             evaluator will suspend execution approximately after every
882             reduction, allowing local variables to be inspected.  This is
883             equivalent to setting a breakpoint at every point in the
884             program.</para>
885         </listitem>
886         <listitem>
887           <para>Execution can take place in <firstterm>tracing
888               mode</firstterm>, in which the evaluator remembers each
889             evaluation step as it happens, but doesn't suspend execution until
890             an actual breakpoint is reached.  When this happens, the history of
891             evaluation steps can be inspected.</para>
892         </listitem>
893         <listitem>
894           <para>Exceptions (e.g. pattern matching failure and
895             <literal>error</literal>) can be treated as breakpoints, to help
896             locate the source of an exception in the program.</para>
897         </listitem>
898       </itemizedlist>
899     </para>
900       
901     <para>There is currently no support for obtaining a &ldquo;stack
902     trace&rdquo;, but the tracing and history features provide a
903     useful second-best, which will often be enough to establish the
904     context of an error.  For instance, it is possible to break
905     automatically when an exception is thrown, even if it is thrown
906     from within compiled code (see <xref
907     linkend="ghci-debugger-exceptions" />).</para>
908       
909     <sect2 id="breakpoints">
910       <title>Breakpoints and inspecting variables</title>
911       
912       <para>Let's use quicksort as a running example.  Here's the code:</para>
913
914 <programlisting>
915 qsort [] = [] 
916 qsort (a:as) = qsort left ++ [a] ++ qsort right
917   where (left,right) = (filter (&lt;=a) as, filter (&gt;a) as)
918
919 main = print (qsort [8, 4, 0, 3, 1, 23, 11, 18])
920 </programlisting>
921
922       <para>First, load the module into GHCi:</para>
923
924 <screen>
925 Prelude> :l qsort.hs
926 [1 of 1] Compiling Main             ( qsort.hs, interpreted )
927 Ok, modules loaded: Main.
928 *Main>
929       </screen>       
930
931       <para>Now, let's set a breakpoint on the right-hand-side of the second
932         equation of qsort:</para>
933
934 <programlisting>
935 *Main> :break 2
936 Breakpoint 0 activated at qsort.hs:2:15-46
937 *Main>
938 </programlisting>
939       
940       <para>The command <literal>:break 2</literal> sets a breakpoint on line
941         2 of the most recently-loaded module, in this case
942         <literal>qsort.hs</literal>.   Specifically, it picks the
943         leftmost complete subexpression on that line on which to set the
944         breakpoint, which in this case is the expression 
945         <literal>(qsort left ++ [a] ++ qsort right)</literal>.</para>
946
947       <para>Now, we run the program:</para>
948
949 <programlisting>
950 *Main> main
951 Stopped at qsort.hs:2:15-46
952 _result :: [a]
953 a :: a
954 left :: [a]
955 right :: [a]
956 [qsort.hs:2:15-46] *Main>
957 </programlisting>
958
959       <para>Execution has stopped at the breakpoint.  The prompt has changed to
960         indicate that we are currently stopped at a breakpoint, and the location:
961         <literal>[qsort.hs:2:15-46]</literal>.  To further clarify the
962         location, we can use the <literal>:list</literal> command:</para>
963
964 <programlisting>
965 [qsort.hs:2:15-46] *Main> :list 
966 1  qsort [] = [] 
967 2  qsort (a:as) = qsort left ++ [a] ++ qsort right
968 3    where (left,right) = (filter (&lt;=a) as, filter (&gt;a) as)
969 </programlisting>
970
971       <para>The <literal>:list</literal> command lists the source code around
972         the current breakpoint.  If your output device supports it, then GHCi
973         will highlight the active subexpression in bold.</para>
974
975       <para>GHCi has provided bindings for the free variables<footnote><para>We
976             originally provided bindings for all variables in scope, rather
977             than just
978             the free variables of the expression, but found that this affected
979             performance considerably, hence the current restriction to just the
980             free variables.</para>
981         </footnote> of the expression
982         on which the
983         breakpoint was placed (<literal>a</literal>, <literal>left</literal>,
984         <literal>right</literal>), and additionally a binding for the result of
985         the expression (<literal>_result</literal>).  These variables are just
986         like other variables that you might define in GHCi; you
987         can use them in expressions that you type at the prompt, you can ask
988         for their types with <literal>:type</literal>, and so on.  There is one
989         important difference though: these variables may only have partial
990         types.  For example, if we try to display the value of
991         <literal>left</literal>:</para>
992
993 <screen>
994 [qsort.hs:2:15-46] *Main> left
995
996 &lt;interactive&gt;:1:0:
997     Ambiguous type variable `a' in the constraint:
998       `Show a' arising from a use of `print' at &lt;interactive&gt;:1:0-3
999     Cannot resolve unknown runtime types: a
1000     Use :print or :force to determine these types
1001 </screen>
1002
1003       <para>This is because <literal>qsort</literal> is a polymorphic function,
1004         and because GHCi does not carry type information at runtime, it cannot
1005         determine the runtime types of free variables that involve type
1006         variables.  Hence, when you ask to display <literal>left</literal> at
1007         the prompt, GHCi can't figure out which instance of
1008         <literal>Show</literal> to use, so it emits the type error above.</para>
1009
1010       <para>Fortunately, the debugger includes a generic printing command,
1011         <literal>:print</literal>, which can inspect the actual runtime value of a
1012         variable and attempt to reconstruct its type.  If we try it on
1013         <literal>left</literal>:</para>
1014
1015 <screen>
1016 [qsort.hs:2:15-46] *Main> :set -fprint-evld-with-show
1017 [qsort.hs:2:15-46] *Main> :print left
1018 left = (_t1::[a])
1019 </screen>
1020
1021       <para>This isn't particularly enlightening.  What happened is that
1022         <literal>left</literal> is bound to an unevaluated computation (a
1023         suspension, or <firstterm>thunk</firstterm>), and
1024         <literal>:print</literal> does not force any evaluation.  The idea is
1025         that <literal>:print</literal> can be used to inspect values at a
1026         breakpoint without any unfortunate side effects.  It won't force any
1027         evaluation, which could cause the program to give a different answer
1028         than it would normally, and hence it won't cause any exceptions to be
1029         raised, infinite loops, or further breakpoints to be triggered (see
1030         <xref linkend="nested-breakpoints" />).
1031         Rather than forcing thunks, <literal>:print</literal>
1032         binds each thunk to a fresh variable beginning with an
1033         underscore, in this case
1034         <literal>_t1</literal>.</para>
1035
1036       <para>The flag <literal>-fprint-evld-with-show</literal> instructs
1037       <literal>:print</literal> to reuse
1038       available <literal>Show</literal> instances when possible. This happens
1039       only when the contents of the variable being inspected 
1040       are completely evaluated.</para>
1041
1042
1043       <para>If we aren't concerned about preserving the evaluatedness of a
1044         variable, we can use <literal>:force</literal> instead of
1045         <literal>:print</literal>.  The <literal>:force</literal> command
1046         behaves exactly like <literal>:print</literal>, except that it forces
1047         the evaluation of any thunks it encounters:</para>
1048
1049 <screen>
1050 [qsort.hs:2:15-46] *Main> :force left
1051 left = [4,0,3,1]
1052 </screen>
1053
1054       <para>Now, since <literal>:force</literal> has inspected the runtime
1055         value of <literal>left</literal>, it has reconstructed its type.  We
1056         can see the results of this type reconstruction:</para>
1057
1058 <screen>
1059 [qsort.hs:2:15-46] *Main> :show bindings
1060 _result :: [Integer]
1061 a :: Integer
1062 left :: [Integer]
1063 right :: [Integer]
1064 _t1 :: [Integer]
1065 </screen>
1066
1067       <para>Not only do we now know the type of <literal>left</literal>, but
1068         all the other partial types have also been resolved.  So we can ask
1069         for the value of <literal>a</literal>, for example:</para>
1070
1071 <screen>
1072 [qsort.hs:2:15-46] *Main> a
1073 8
1074 </screen>
1075       
1076       <para>You might find it useful to use Haskell's
1077         <literal>seq</literal> function to evaluate individual thunks rather
1078         than evaluating the whole expression with <literal>:force</literal>.
1079         For example:</para>
1080
1081 <screen>
1082 [qsort.hs:2:15-46] *Main> :print right
1083 right = (_t1::[Integer])
1084 [qsort.hs:2:15-46] *Main> seq _t1 ()
1085 ()
1086 [qsort.hs:2:15-46] *Main> :print right
1087 right = 23 : (_t2::[Integer])
1088 </screen>
1089
1090       <para>We evaluated only the <literal>_t1</literal> thunk, revealing the
1091         head of the list, and the tail is another thunk now bound to
1092         <literal>_t2</literal>.  The <literal>seq</literal> function is a
1093         little inconvenient to use here, so you might want to use
1094         <literal>:def</literal> to make a nicer interface (left as an exercise
1095         for the reader!).</para>
1096
1097       <para>Finally, we can continue the current execution:</para>
1098
1099 <screen>
1100 [qsort.hs:2:15-46] *Main> :continue
1101 Stopped at qsort.hs:2:15-46
1102 _result :: [a]
1103 a :: a
1104 left :: [a]
1105 right :: [a]
1106 [qsort.hs:2:15-46] *Main> 
1107 </screen>
1108
1109       <para>The execution continued at the point it previously stopped, and has
1110         now stopped at the breakpoint for a second time.</para>
1111
1112
1113       <sect3 id="setting-breakpoints">
1114         <title>Setting breakpoints</title>
1115
1116         <para>Breakpoints can be set in various ways.  Perhaps the easiest way to
1117           set a breakpoint is to name a top-level function:</para>
1118
1119 <screen>
1120    :break <replaceable>identifier</replaceable>
1121 </screen>
1122
1123       <para>Where <replaceable>identifier</replaceable> names any top-level
1124         function in an interpreted module currently loaded into GHCi (qualified
1125         names may be used).  The breakpoint will be set on the body of the
1126         function, when it is fully applied but before any pattern matching has
1127         taken place.</para>
1128
1129       <para>Breakpoints can also be set by line (and optionally column)
1130         number:</para>
1131
1132 <screen>
1133    :break <replaceable>line</replaceable>
1134    :break <replaceable>line</replaceable> <replaceable>column</replaceable>
1135    :break <replaceable>module</replaceable> <replaceable>line</replaceable>
1136    :break <replaceable>module</replaceable> <replaceable>line</replaceable> <replaceable>column</replaceable> 
1137 </screen>
1138
1139       <para>When a breakpoint is set on a particular line, GHCi sets the
1140         breakpoint on the
1141         leftmost subexpression that begins and ends on that line.  If two
1142         complete subexpressions start at the same 
1143         column, the longest one is picked.  If there is no complete
1144         subexpression on the line, then the leftmost expression starting on
1145         the line is picked, and failing that the rightmost expression that
1146         partially or completely covers the line.</para>
1147
1148       <para>When a breakpoint is set on a particular line and column, GHCi
1149         picks the smallest subexpression that encloses that location on which
1150         to set the breakpoint.  Note: GHC considers the TAB character to have a
1151         width of 1, wherever it occurs; in other words it counts
1152           characters, rather than columns.  This matches what some editors do,
1153           and doesn't match others.  The best advice is to avoid tab
1154           characters in your source code altogether (see
1155           <option>-fwarn-tabs</option> in <xref linkend="options-sanity"
1156             />).</para> 
1157
1158       <para>If the module is omitted, then the most recently-loaded module is
1159         used.</para>
1160
1161       <para>Not all subexpressions are potential breakpoint locations.  Single
1162         variables are typically not considered to be breakpoint locations
1163         (unless the variable is the right-hand-side of a function definition,
1164         lambda, or case alternative).  The rule of thumb is that all redexes
1165         are breakpoint locations, together with the bodies of functions,
1166         lambdas, case alternatives and binding statements.  There is normally
1167         no breakpoint on a let expression, but there will always be a
1168         breakpoint on its body, because we are usually interested in inspecting
1169         the values of the variables bound by the let.</para>
1170
1171       </sect3>
1172       <sect3>
1173         <title>Listing and deleting breakpoints</title>
1174
1175         <para>The list of breakpoints currently enabled can be displayed using
1176           <literal>:show&nbsp;breaks</literal>:</para>
1177 <screen>
1178 *Main> :show breaks
1179 [0] Main qsort.hs:1:11-12
1180 [1] Main qsort.hs:2:15-46
1181 </screen>
1182
1183         <para>To delete a breakpoint, use the <literal>:delete</literal>
1184           command with the number given in the output from <literal>:show&nbsp;breaks</literal>:</para>
1185
1186 <screen>
1187 *Main> :delete 0
1188 *Main> :show breaks
1189 [1] Main qsort.hs:2:15-46
1190 </screen>        
1191
1192         <para>To delete all breakpoints at once, use <literal>:delete *</literal>.</para>
1193
1194     </sect3>
1195     </sect2>
1196
1197     <sect2 id="single-stepping">
1198       <title>Single-stepping</title>
1199
1200       <para>Single-stepping is a great way to visualise the execution of your
1201         program, and it is also a useful tool for identifying the source of a
1202         bug. GHCi offers two variants of stepping. Use 
1203         <literal>:step</literal>  to enable all the
1204         breakpoints in the program, and execute until the next breakpoint is
1205         reached. Use <literal>:steplocal</literal> to limit the set
1206         of enabled breakpoints to those in the current top level function.
1207         Similarly, use <literal>:stepmodule</literal> to single step only on
1208         breakpoints contained in the current module.
1209         For example:</para>
1210
1211 <screen>
1212 *Main> :step main
1213 Stopped at qsort.hs:5:7-47
1214 _result :: IO ()
1215 </screen>
1216
1217       <para>The command <literal>:step
1218         <replaceable>expr</replaceable></literal> begins the evaluation of
1219         <replaceable>expr</replaceable> in single-stepping mode.  If
1220         <replaceable>expr</replaceable> is omitted, then it single-steps from
1221         the current breakpoint. <literal>:stepover</literal> 
1222         works similarly.</para>
1223
1224       <para>The <literal>:list</literal> command is particularly useful when
1225         single-stepping, to see where you currently are:</para>
1226
1227 <screen>
1228 [qsort.hs:5:7-47] *Main> :list
1229 4  
1230 5  main = print (qsort [8, 4, 0, 3, 1, 23, 11, 18])
1231 6  
1232 [qsort.hs:5:7-47] *Main>
1233 </screen>
1234
1235       <para>In fact, GHCi provides a way to run a command when a breakpoint is
1236         hit, so we can make it automatically do
1237         <literal>:list</literal>:</para>
1238
1239 <screen>
1240 [qsort.hs:5:7-47] *Main> :set stop :list
1241 [qsort.hs:5:7-47] *Main> :step
1242 Stopped at qsort.hs:5:14-46
1243 _result :: [Integer]
1244 4  
1245 5  main = print (qsort [8, 4, 0, 3, 1, 23, 11, 18])
1246 6  
1247 [qsort.hs:5:14-46] *Main>
1248 </screen>
1249     </sect2>
1250
1251     <sect2 id="nested-breakpoints">
1252       <title>Nested breakpoints</title>
1253       <para>When GHCi is stopped at a breakpoint, and an expression entered at
1254         the prompt triggers a
1255         second breakpoint, the new breakpoint becomes the &ldquo;current&rdquo;
1256       one, and the old one is saved on a stack.  An arbitrary number of
1257         breakpoint contexts can be built up in this way.  For example:</para>
1258
1259 <screen>
1260 [qsort.hs:2:15-46] *Main> :st qsort [1,3]
1261 Stopped at qsort.hs:(1,0)-(3,55)
1262 _result :: [a]
1263 ... [qsort.hs:(1,0)-(3,55)] *Main>
1264 </screen>
1265
1266       <para>While stopped at the breakpoint on line 2 that we set earlier, we
1267         started a new evaluation with <literal>:step qsort [1,3]</literal>.
1268         This new evaluation stopped after one step (at the definition of
1269         <literal>qsort</literal>).  The prompt has changed, now prefixed with
1270         <literal>...</literal>, to indicate that there are saved breakpoints
1271         beyond the current one.  To see the stack of contexts, use
1272         <literal>:show context</literal>:</para>
1273
1274 <screen>
1275 ... [qsort.hs:(1,0)-(3,55)] *Main> :show context
1276 --> main
1277   Stopped at qsort.hs:2:15-46
1278 --> qsort [1,3]
1279   Stopped at qsort.hs:(1,0)-(3,55)
1280 ... [qsort.hs:(1,0)-(3,55)] *Main>
1281 </screen>
1282
1283         <para>To abandon the current evaluation, use
1284         <literal>:abandon</literal>:</para>
1285
1286 <screen>
1287 ... [qsort.hs:(1,0)-(3,55)] *Main> :abandon
1288 [qsort.hs:2:15-46] *Main> :abandon
1289 *Main>
1290 </screen>
1291     </sect2>
1292
1293     <sect2 id="ghci-debugger-result">
1294       <title>The <literal>_result</literal> variable</title>
1295       <para>When stopped at a breakpoint or single-step, GHCi binds the
1296         variable <literal>_result</literal> to the value of the currently
1297         active expression.  The value of <literal>_result</literal> is
1298         presumably not available yet, because we stopped its evaluation, but it
1299         can be forced: if the type is known and showable, then just entering
1300         <literal>_result</literal> at the prompt will show it.  However,
1301         there's one caveat to doing this: evaluating <literal>_result</literal>
1302         will be likely to trigger further breakpoints, starting with the
1303         breakpoint we are currently stopped at (if we stopped at a real
1304         breakpoint, rather than due to <literal>:step</literal>).  So it will
1305         probably be necessary to issue a <literal>:continue</literal>
1306         immediately when evaluating <literal>_result</literal>.  Alternatively,
1307         you can use <literal>:force</literal> which ignores breakpoints.</para>
1308     </sect2>
1309
1310     <sect2 id="tracing">
1311       <title>Tracing and history</title>
1312
1313       <para>A question that we often want to ask when debugging a program is
1314         &ldquo;how did I get here?&rdquo;.  Traditional imperative debuggers
1315         usually provide some kind of stack-tracing feature that lets you see
1316         the stack of active function calls (sometimes called the &ldquo;lexical
1317         call stack&rdquo;), describing a path through the code
1318         to the current location.  Unfortunately this is hard to provide in
1319         Haskell, because execution proceeds on a demand-driven basis, rather
1320         than a depth-first basis as in strict languages.  The
1321         &ldquo;stack&ldquo; in GHC's execution engine bears little
1322         resemblance to the lexical call stack.  Ideally GHCi would maintain a
1323         separate lexical call stack in addition to the dynamic call stack, and
1324         in fact this is exactly
1325         what our profiling system does (<xref linkend="profiling" />), and what
1326         some other Haskell debuggers do.  For the time being, however, GHCi
1327         doesn't maintain a lexical call stack (there are some technical
1328         challenges to be overcome).  Instead, we provide a way to backtrack from a
1329         breakpoint to previous evaluation steps: essentially this is like
1330         single-stepping backwards, and should in many cases provide enough
1331         information to answer the &ldquo;how did I get here?&rdquo;
1332         question.</para>
1333
1334       <para>To use tracing, evaluate an expression with the
1335         <literal>:trace</literal> command.  For example, if we set a breakpoint
1336         on the base case of <literal>qsort</literal>:</para>
1337
1338 <screen>
1339 *Main&gt; :list qsort
1340 1  qsort [] = [] 
1341 2  qsort (a:as) = qsort left ++ [a] ++ qsort right
1342 3    where (left,right) = (filter (&lt;=a) as, filter (&gt;a) as)
1343 4  
1344 *Main&gt; :b 1
1345 Breakpoint 1 activated at qsort.hs:1:11-12
1346 *Main&gt; 
1347 </screen>
1348
1349       <para>and then run a small <literal>qsort</literal> with
1350         tracing:</para>
1351
1352 <screen>
1353 *Main> :trace qsort [3,2,1]
1354 Stopped at qsort.hs:1:11-12
1355 _result :: [a]
1356 [qsort.hs:1:11-12] *Main>
1357 </screen>
1358
1359       <para>We can now inspect the history of evaluation steps:</para>
1360
1361 <screen>
1362 [qsort.hs:1:11-12] *Main> :hist
1363 -1  : qsort.hs:3:24-38
1364 -2  : qsort.hs:3:23-55
1365 -3  : qsort.hs:(1,0)-(3,55)
1366 -4  : qsort.hs:2:15-24
1367 -5  : qsort.hs:2:15-46
1368 -6  : qsort.hs:3:24-38
1369 -7  : qsort.hs:3:23-55
1370 -8  : qsort.hs:(1,0)-(3,55)
1371 -9  : qsort.hs:2:15-24
1372 -10 : qsort.hs:2:15-46
1373 -11 : qsort.hs:3:24-38
1374 -12 : qsort.hs:3:23-55
1375 -13 : qsort.hs:(1,0)-(3,55)
1376 -14 : qsort.hs:2:15-24
1377 -15 : qsort.hs:2:15-46
1378 -16 : qsort.hs:(1,0)-(3,55)
1379 &lt;end of history&gt;
1380 </screen>
1381
1382       <para>To examine one of the steps in the history, use
1383         <literal>:back</literal>:</para>
1384
1385 <screen>
1386 [qsort.hs:1:11-12] *Main> :back
1387 Logged breakpoint at qsort.hs:3:24-38
1388 _result :: [a]
1389 as :: [a]
1390 a :: a
1391 [-1: qsort.hs:3:24-38] *Main> 
1392 </screen>
1393
1394       <para>Note that the local variables at each step in the history have been
1395         preserved, and can be examined as usual.  Also note that the prompt has
1396         changed to indicate that we're currently examining the first step in
1397         the history: <literal>-1</literal>.  The command
1398         <literal>:forward</literal> can be used to traverse forward in the
1399         history.</para>
1400
1401       <para>The <literal>:trace</literal> command can be used with or without
1402         an expression.  When used without an expression, tracing begins from
1403         the current breakpoint, just like <literal>:step</literal>.</para>
1404
1405       <para>The history is only available when
1406         using <literal>:trace</literal>; the reason for this is we found that
1407         logging each breakpoint in the history cuts performance by a factor of
1408         2 or more.  GHCi remembers the last 50 steps in the history (perhaps in
1409         the future we'll make this configurable).</para>
1410     </sect2>
1411
1412     <sect2 id="ghci-debugger-exceptions">
1413       <title>Debugging exceptions</title>
1414       <para>Another common question that comes up when debugging is
1415         &ldquo;where did this exception come from?&rdquo;.  Exceptions such as
1416         those raised by <literal>error</literal> or <literal>head []</literal>
1417         have no context information attached to them.  Finding which
1418         particular call to <literal>head</literal> in your program resulted in
1419         the error can be a painstaking process, usually involving
1420         <literal>Debug.Trace.trace</literal>, or compiling with
1421         profiling and using <literal>+RTS -xc</literal> (see <xref
1422           linkend="prof-time-options" />).</para>
1423
1424       <para>The GHCi debugger offers a way to hopefully shed some light on
1425         these errors quickly and without modifying or recompiling the source
1426         code.  One way would be to set a breakpoint on the location in the
1427         source code that throws the exception, and then use
1428         <literal>:trace</literal> and <literal>:history</literal> to establish
1429         the context.  However, <literal>head</literal> is in a library and
1430         we can't set a breakpoint on it directly.  For this reason, GHCi
1431         provides the flags <literal>-fbreak-on-exception</literal> which causes
1432         the evaluator to stop when an exception is thrown, and <literal>
1433         -fbreak-on-error</literal>, which works similarly but stops only on 
1434         uncaught exceptions. When stopping at an exception, GHCi will act 
1435         just as it does when a breakpoint is hit, with the deviation that it
1436         will not show you any source code location. Due to this, these 
1437         commands are only really useful in conjunction with
1438         <literal>:trace</literal>, in order to log the steps leading up to the
1439         exception.  For example:</para>
1440
1441 <screen>
1442 *Main> :set -fbreak-on-exception
1443 *Main> :trace qsort ("abc" ++ undefined)
1444 "Stopped at &lt;exception thrown&gt;
1445 _exception :: e
1446 [&lt;exception thrown&gt;] *Main&gt; :hist
1447 -1  : qsort.hs:3:24-38
1448 -2  : qsort.hs:3:23-55
1449 -3  : qsort.hs:(1,0)-(3,55)
1450 -4  : qsort.hs:2:15-24
1451 -5  : qsort.hs:2:15-46
1452 -6  : qsort.hs:(1,0)-(3,55)
1453 &lt;end of history&gt;
1454 [&lt;exception thrown&gt;] *Main&gt; :back
1455 Logged breakpoint at qsort.hs:3:24-38
1456 _result :: [a]
1457 as :: [a]
1458 a :: a
1459 [-1: qsort.hs:3:24-38] *Main&gt; :force as
1460 *** Exception: Prelude.undefined
1461 [-1: qsort.hs:3:24-38] *Main&gt; :print as
1462 as = 'b' : 'c' : (_t1::[Char])
1463 </screen>
1464
1465       <para>The exception itself is bound to a new variable,
1466         <literal>_exception</literal>.</para>
1467
1468       <para>Breaking on exceptions is particularly useful for finding out what
1469         your program was doing when it was in an infinite loop.  Just hit
1470         Control-C, and examine the history to find out what was going
1471         on.</para>
1472     </sect2>
1473
1474     <sect2><title>Example: inspecting functions</title>
1475       <para>
1476         It is possible to use the debugger to examine function values. 
1477         When we are at a breakpoint and a function is in scope, the debugger
1478         cannot show 
1479         you the source code for it; however, it is possible to get some 
1480         information by applying it to some arguments and  observing the result. 
1481       </para>
1482
1483       <para>
1484         The process is slightly complicated when the binding is polymorphic. 
1485         We show the process by means of an example.
1486         To keep things simple, we will use the well known <literal>map</literal> function:
1487 <programlisting>
1488 import Prelude hiding (map)
1489
1490 map :: (a->b) -> [a] -> [b]
1491 map f [] = []
1492 map f (x:xs) = f x : map f xs
1493 </programlisting>
1494       </para>
1495
1496       <para>
1497         We set a breakpoint on <literal>map</literal>, and call it.
1498 <screen>
1499 *Main> :break 5
1500 Breakpoint 0 activated at  map.hs:5:15-28
1501 *Main> map Just [1..5]
1502 Stopped at map.hs:(4,0)-(5,12)
1503 _result :: [b]
1504 x :: a
1505 f :: a -> b
1506 xs :: [a]
1507 </screen>
1508       GHCi tells us that, among other bindings, <literal>f</literal> is in scope. 
1509       However, its type is not fully known yet,  
1510       and thus it is not possible to apply it to any 
1511       arguments. Nevertheless, observe that the type of its first argument is the
1512       same as the type of <literal>x</literal>, and its result type is shared
1513         with <literal>_result</literal>.
1514       </para>
1515
1516       <para>
1517         As we demonstrated earlier (<xref linkend="breakpoints" />),  the
1518         debugger has some intelligence built-in to update the type of 
1519         <literal>f</literal> whenever the types of <literal>x</literal> or 
1520         <literal>_result</literal> are discovered.  So what we do in this
1521         scenario is
1522         force <literal>x</literal> a bit, in order to recover both its type 
1523       and the argument part of <literal>f</literal>.  
1524 <screen>
1525 *Main> seq x ()
1526 *Main> :print x
1527 x = 1
1528 </screen>
1529       </para>
1530       <para>
1531         We can check now that as expected, the type of <literal>x</literal>
1532         has been reconstructed, and with it the 
1533         type of <literal>f</literal> has been too:</para>
1534 <screen>
1535 *Main> :t x
1536 x :: Integer
1537 *Main> :t f
1538 f :: Integer -> b
1539 </screen>
1540       <para>
1541         From here, we can apply f to any argument of type Integer and observe
1542         the results. 
1543 <screen><![CDATA[
1544 *Main> let b = f 10
1545 *Main> :t b
1546 b :: b
1547 *Main> b
1548 <interactive>:1:0:
1549     Ambiguous type variable `b' in the constraint:
1550       `Show b' arising from a use of `print' at <interactive>:1:0
1551 *Main> :p b
1552 b = (_t2::a)
1553 *Main> seq b ()
1554 ()
1555 *Main> :t b
1556 b :: a
1557 *Main> :p b
1558 b = Just 10
1559 *Main> :t b
1560 b :: Maybe Integer
1561 *Main> :t f
1562 f :: Integer -> Maybe Integer
1563 *Main> f 20
1564 Just 20
1565 *Main> map f [1..5]
1566 [Just 1, Just 2, Just 3, Just 4, Just 5]
1567 ]]></screen>
1568       In the first application of <literal>f</literal>, we had to do 
1569       some more type reconstruction
1570       in order to recover the result type of <literal>f</literal>. 
1571       But after that, we are free to use 
1572       <literal>f</literal> normally.
1573      </para>
1574     </sect2>
1575
1576     <sect2><title>Limitations</title>
1577       <itemizedlist>
1578         <listitem>
1579           <para>When stopped at a breakpoint, if you try to evaluate a variable
1580             that is already under evaluation, the second evaluation will hang.
1581             The reason is
1582             that GHC knows the variable is under evaluation, so the new
1583             evaluation just waits for the result before continuing, but of
1584             course this isn't going to happen because the first evaluation is
1585             stopped at a breakpoint. Control-C can interrupt the hung
1586             evaluation and return to the prompt.</para>
1587           <para>The most common way this can happen is when you're evaluating a
1588             CAF (e.g. main), stop at a breakpoint, and ask for the value of the
1589             CAF at the prompt again.</para>
1590         </listitem>
1591         <listitem><para>
1592           Implicit parameters (see <xref linkend="implicit-parameters"/>) are only available 
1593           at the scope of a breakpoint if there is an explicit type signature.
1594         </para>
1595         </listitem>
1596       </itemizedlist>
1597     </sect2>
1598   </sect1>
1599
1600   <sect1 id="ghci-invocation">
1601     <title>Invoking GHCi</title>
1602     <indexterm><primary>invoking</primary><secondary>GHCi</secondary></indexterm>
1603     <indexterm><primary><option>&ndash;&ndash;interactive</option></primary></indexterm>
1604
1605     <para>GHCi is invoked with the command <literal>ghci</literal> or
1606     <literal>ghc &ndash;&ndash;interactive</literal>.  One or more modules or
1607     filenames can also be specified on the command line; this
1608     instructs GHCi to load the specified modules or filenames (and all
1609     the modules they depend on), just as if you had said
1610     <literal>:load <replaceable>modules</replaceable></literal> at the
1611     GHCi prompt (see <xref linkend="ghci-commands" />).  For example, to
1612     start GHCi and load the program whose topmost module is in the
1613     file <literal>Main.hs</literal>, we could say:</para>
1614
1615 <screen>
1616 $ ghci Main.hs
1617 </screen>
1618
1619     <para>Most of the command-line options accepted by GHC (see <xref
1620     linkend="using-ghc"/>) also make sense in interactive mode.  The ones
1621     that don't make sense are mostly obvious.</para>
1622
1623     <sect2>
1624       <title>Packages</title>
1625       <indexterm><primary>packages</primary><secondary>with GHCi</secondary></indexterm>
1626
1627       <para>Most packages (see <xref linkend="using-packages"/>) are
1628       available without needing to specify any extra flags at all:
1629       they will be automatically loaded the first time they are
1630       needed.</para>
1631
1632       <para>For hidden packages, however, you need to request the
1633       package be loaded by using the <literal>-package</literal> flag:</para>
1634
1635 <screen>
1636 $ ghci -package readline
1637 GHCi, version 6.8.1: http://www.haskell.org/ghc/  :? for help
1638 Loading package base ... linking ... done.
1639 Loading package readline-1.0 ... linking ... done.
1640 Prelude> 
1641 </screen>
1642
1643       <para>The following command works to load new packages into a
1644       running GHCi:</para>
1645
1646 <screen>
1647 Prelude> :set -package <replaceable>name</replaceable>
1648 </screen>
1649
1650       <para>But note that doing this will cause all currently loaded
1651       modules to be unloaded, and you'll be dumped back into the
1652       <literal>Prelude</literal>.</para>
1653     </sect2>
1654
1655     <sect2>
1656       <title>Extra libraries</title>
1657       <indexterm><primary>libraries</primary><secondary>with GHCi</secondary></indexterm>
1658       
1659       <para>Extra libraries may be specified on the command line using
1660       the normal <literal>-l<replaceable>lib</replaceable></literal>
1661       option.  (The term <emphasis>library</emphasis> here refers to
1662       libraries of foreign object code; for using libraries of Haskell
1663       source code, see <xref linkend="ghci-modules-filenames"/>.) For
1664       example, to load the &ldquo;m&rdquo; library:</para>
1665
1666 <screen>
1667 $ ghci -lm
1668 </screen>
1669
1670       <para>On systems with <literal>.so</literal>-style shared
1671       libraries, the actual library loaded will the
1672       <filename>lib<replaceable>lib</replaceable>.so</filename>.  GHCi
1673       searches the following places for libraries, in this order:</para>
1674
1675       <itemizedlist>
1676         <listitem>
1677           <para>Paths specified using the
1678           <literal>-L<replaceable>path</replaceable></literal>
1679           command-line option,</para>
1680         </listitem>
1681         <listitem>
1682           <para>the standard library search path for your system,
1683           which on some systems may be overridden by setting the
1684           <literal>LD_LIBRARY_PATH</literal> environment
1685           variable.</para>
1686         </listitem>
1687       </itemizedlist>
1688
1689       <para>On systems with <literal>.dll</literal>-style shared
1690       libraries, the actual library loaded will be
1691       <filename><replaceable>lib</replaceable>.dll</filename>.  Again,
1692       GHCi will signal an error if it can't find the library.</para>
1693
1694       <para>GHCi can also load plain object files
1695       (<literal>.o</literal> or <literal>.obj</literal> depending on
1696       your platform) from the command-line.  Just add the name the
1697       object file to the command line.</para>
1698
1699       <para>Ordering of <option>-l</option> options matters: a library
1700       should be mentioned <emphasis>before</emphasis> the libraries it
1701       depends on (see <xref linkend="options-linker"/>).</para>
1702     </sect2>
1703
1704   </sect1>
1705
1706   <sect1 id="ghci-commands">
1707     <title>GHCi commands</title>
1708
1709     <para>GHCi commands all begin with
1710     &lsquo;<literal>:</literal>&rsquo; and consist of a single command
1711     name followed by zero or more parameters.  The command name may be
1712     abbreviated, with ambiguities being resolved in favour of the more
1713     commonly used commands.</para>
1714
1715     <variablelist>
1716       <varlistentry>
1717         <term>
1718           <literal>:abandon</literal>
1719           <indexterm><primary><literal>:abandon</literal></primary></indexterm>
1720         </term>
1721         <listitem>
1722           <para>Abandons the current evaluation (only available when stopped at
1723           a breakpoint).</para>
1724         </listitem>
1725       </varlistentry>
1726
1727       <varlistentry>
1728         <term>
1729           <literal>:add</literal> <replaceable>module</replaceable> ...
1730           <indexterm><primary><literal>:add</literal></primary></indexterm>
1731         </term>
1732         <listitem>
1733           <para>Add <replaceable>module</replaceable>(s) to the
1734           current <firstterm>target set</firstterm>, and perform a
1735           reload.</para>
1736         </listitem>
1737       </varlistentry>
1738
1739       <varlistentry>
1740         <term>
1741           <literal>:back</literal>
1742           <indexterm><primary><literal>:back</literal></primary></indexterm>
1743         </term>
1744         <listitem>
1745           <para>Travel back one step in the history.  See <xref
1746               linkend="tracing" />.  See also:
1747             <literal>:trace</literal>, <literal>:history</literal>,
1748             <literal>:forward</literal>.</para>
1749         </listitem>
1750       </varlistentry>
1751
1752       <varlistentry>
1753         <term>
1754           <literal>:break [<replaceable>identifier</replaceable> |
1755             [<replaceable>module</replaceable>] <replaceable>line</replaceable>
1756             [<replaceable>column</replaceable>]]</literal>
1757         </term>
1758           <indexterm><primary><literal>:break</literal></primary></indexterm>
1759         <listitem>
1760           <para>Set a breakpoint on the specified function or line and
1761               column.  See <xref linkend="setting-breakpoints" />.</para>
1762         </listitem>
1763       </varlistentry>
1764
1765       <varlistentry>
1766         <term>
1767           <literal>:browse</literal><optional><literal>!</literal></optional> <optional><optional><literal>*</literal></optional><replaceable>module</replaceable></optional> ...
1768           <indexterm><primary><literal>:browse</literal></primary></indexterm>
1769         </term>
1770         <listitem>
1771           <para>Displays the identifiers defined by the module
1772           <replaceable>module</replaceable>, which must be either
1773           loaded into GHCi or be a member of a package.  If
1774           <replaceable>module</replaceable> is omitted, the most
1775           recently-loaded module is used.</para>
1776
1777           <para>If the <literal>*</literal> symbol is placed before
1778           the module name, then <emphasis>all</emphasis> the
1779           identifiers in scope in <replaceable>module</replaceable> are
1780           shown; otherwise the list is limited to the exports of
1781           <replaceable>module</replaceable>.  The
1782           <literal>*</literal>-form is only available for modules
1783           which are interpreted; for compiled modules (including
1784           modules from packages) only the non-<literal>*</literal>
1785     form of <literal>:browse</literal> is available.
1786     If the <literal>!</literal> symbol is appended to the
1787     command, data constructors and class methods will be 
1788     listed individually, otherwise, they will only be listed
1789     in the context of their data type or class declaration. 
1790     The <literal>!</literal>-form also annotates the listing 
1791     with comments giving possible imports for each group of 
1792     entries.</para>
1793 <screen>
1794 Prelude> :browse! Data.Maybe
1795 -- not currently imported
1796 Data.Maybe.catMaybes :: [Maybe a] -> [a]
1797 Data.Maybe.fromJust :: Maybe a -> a
1798 Data.Maybe.fromMaybe :: a -> Maybe a -> a
1799 Data.Maybe.isJust :: Maybe a -> Bool
1800 Data.Maybe.isNothing :: Maybe a -> Bool
1801 Data.Maybe.listToMaybe :: [a] -> Maybe a
1802 Data.Maybe.mapMaybe :: (a -> Maybe b) -> [a] -> [b]
1803 Data.Maybe.maybeToList :: Maybe a -> [a]
1804 -- imported via Prelude
1805 Just :: a -> Maybe a
1806 data Maybe a = Nothing | Just a
1807 Nothing :: Maybe a
1808 maybe :: b -> (a -> b) -> Maybe a -> b
1809 </screen>
1810   <para>
1811     This output shows that, in the context of the current session, in the scope
1812     of <literal>Prelude</literal>, the first group of items from
1813     <literal>Data.Maybe</literal> have not been imported (but are available in
1814     fully qualified form in the GHCi session - see <xref
1815       linkend="ghci-scope"/>), whereas the second group of items have been
1816     imported via <literal>Prelude</literal> and are therefore available either
1817     unqualified, or with a <literal>Prelude.</literal> qualifier.
1818   </para>
1819         </listitem>
1820       </varlistentry>
1821
1822       <varlistentry>
1823         <term>
1824           <literal>:cd</literal> <replaceable>dir</replaceable>
1825           <indexterm><primary><literal>:cd</literal></primary></indexterm>
1826         </term>
1827         <listitem>
1828           <para>Changes the current working directory to
1829           <replaceable>dir</replaceable>.  A
1830           &lsquo;<literal>&tilde;</literal>&rsquo; symbol at the
1831           beginning of <replaceable>dir</replaceable> will be replaced
1832           by the contents of the environment variable
1833           <literal>HOME</literal>.</para>
1834
1835           <para>NOTE: changing directories causes all currently loaded
1836           modules to be unloaded.  This is because the search path is
1837           usually expressed using relative directories, and changing
1838           the search path in the middle of a session is not
1839           supported.</para>
1840         </listitem>
1841       </varlistentry>
1842
1843       <varlistentry>
1844         <term>
1845           <literal>:cmd</literal> <replaceable>expr</replaceable>
1846           <indexterm><primary><literal>:cmd</literal></primary></indexterm>
1847         </term>
1848         <listitem>
1849           <para>Executes <replaceable>expr</replaceable> as a computation of
1850             type <literal>IO String</literal>, and then executes the resulting
1851             string as a list of GHCi commands.  Multiple commands are separated
1852             by newlines.  The <literal>:cmd</literal> command is useful with
1853             <literal>:def</literal> and <literal>:set stop</literal>.</para>
1854         </listitem>
1855       </varlistentry>
1856
1857       <varlistentry>
1858         <term>
1859           <literal>:continue</literal> 
1860           <indexterm><primary><literal>:continue</literal></primary></indexterm>
1861         </term>
1862         <listitem><para>Continue the current evaluation, when stopped at a
1863             breakpoint.</para>
1864         </listitem>
1865       </varlistentry>
1866
1867       <varlistentry>
1868         <term>
1869           <literal>:ctags</literal> <optional><replaceable>filename</replaceable></optional>
1870           <literal>:etags</literal> <optional><replaceable>filename</replaceable></optional>
1871           <indexterm><primary><literal>:etags</literal></primary>
1872           </indexterm>
1873           <indexterm><primary><literal>:etags</literal></primary>
1874           </indexterm>
1875         </term>
1876         <listitem>
1877           <para>Generates a &ldquo;tags&rdquo; file for Vi-style editors
1878             (<literal>:ctags</literal>) or
1879         Emacs-style editors (<literal>:etags</literal>).  If
1880             no filename is specified, the default <filename>tags</filename> or
1881             <filename>TAGS</filename> is
1882             used, respectively.  Tags for all the functions, constructors and
1883             types in the currently loaded modules are created.  All modules must
1884             be interpreted for these commands to work.</para>
1885           <para>See also <xref linkend="hasktags" />.</para>
1886         </listitem>
1887       </varlistentry>
1888
1889       <varlistentry>
1890         <term>
1891           <literal>:def<optional>!</optional> <optional><replaceable>name</replaceable> <replaceable>expr</replaceable></optional></literal>
1892           <indexterm><primary><literal>:def</literal></primary></indexterm>
1893         </term>
1894         <listitem>
1895           <para><literal>:def</literal> is used to define new
1896           commands, or macros, in GHCi.  The command
1897           <literal>:def</literal> <replaceable>name</replaceable>
1898           <replaceable>expr</replaceable> defines a new GHCi command
1899           <literal>:<replaceable>name</replaceable></literal>,
1900           implemented by the Haskell expression
1901           <replaceable>expr</replaceable>, which must have type
1902           <literal>String -> IO String</literal>.  When
1903           <literal>:<replaceable>name</replaceable>
1904           <replaceable>args</replaceable></literal> is typed at the
1905           prompt, GHCi will run the expression
1906           <literal>(<replaceable>name</replaceable>
1907           <replaceable>args</replaceable>)</literal>, take the
1908           resulting <literal>String</literal>, and feed it back into
1909           GHCi as a new sequence of commands.  Separate commands in
1910           the result must be separated by
1911           &lsquo;<literal>\n</literal>&rsquo;.</para>
1912
1913           <para>That's all a little confusing, so here's a few
1914           examples.  To start with, here's a new GHCi command which
1915           doesn't take any arguments or produce any results, it just
1916           outputs the current date &amp; time:</para>
1917
1918 <screen>
1919 Prelude> let date _ = Time.getClockTime >>= print >> return ""
1920 Prelude> :def date date
1921 Prelude> :date
1922 Fri Mar 23 15:16:40 GMT 2001
1923 </screen>
1924
1925           <para>Here's an example of a command that takes an argument.
1926           It's a re-implementation of <literal>:cd</literal>:</para>
1927
1928 <screen>
1929 Prelude> let mycd d = Directory.setCurrentDirectory d >> return ""
1930 Prelude> :def mycd mycd
1931 Prelude> :mycd ..
1932 </screen>
1933
1934           <para>Or I could define a simple way to invoke
1935           &ldquo;<literal>ghc &ndash;&ndash;make Main</literal>&rdquo; in the
1936           current directory:</para>
1937
1938 <screen>
1939 Prelude> :def make (\_ -> return ":! ghc &ndash;&ndash;make Main")
1940 </screen>
1941
1942           <para>We can define a command that reads GHCi input from a
1943           file.  This might be useful for creating a set of bindings
1944           that we want to repeatedly load into the GHCi session:</para>
1945
1946 <screen>
1947 Prelude> :def . readFile
1948 Prelude> :. cmds.ghci
1949 </screen>
1950
1951           <para>Notice that we named the command
1952           <literal>:.</literal>, by analogy with the
1953           &lsquo;<literal>.</literal>&rsquo; Unix shell command that
1954           does the same thing.</para>
1955
1956           <para>Typing <literal>:def</literal> on its own lists the
1957           currently-defined macros.  Attempting to redefine an
1958           existing command name results in an error unless the
1959           <literal>:def!</literal> form is used, in which case the old
1960           command with that name is silently overwritten.</para>
1961         </listitem>
1962       </varlistentry>
1963
1964       <varlistentry>
1965         <term>
1966           <literal>:delete * | <replaceable>num</replaceable> ...</literal> 
1967           <indexterm><primary><literal>:delete</literal></primary></indexterm>
1968         </term>
1969         <listitem>
1970           <para>Delete one or more breakpoints by number (use <literal>:show
1971               breaks</literal> to see the number of each breakpoint).  The
1972             <literal>*</literal> form deletes all the breakpoints.</para>
1973         </listitem>
1974       </varlistentry>
1975
1976       <varlistentry>
1977         <term>
1978           <literal>:edit <optional><replaceable>file</replaceable></optional></literal>
1979           <indexterm><primary><literal>:edit</literal></primary></indexterm>
1980         </term>
1981         <listitem>
1982           <para>Opens an editor to edit the file
1983           <replaceable>file</replaceable>, or the most recently loaded
1984           module if <replaceable>file</replaceable> is omitted.  The
1985           editor to invoke is taken from the <literal>EDITOR</literal>
1986           environment variable, or a default editor on your system if
1987           <literal>EDITOR</literal> is not set.  You can change the
1988           editor using <literal>:set editor</literal>.</para>
1989         </listitem>
1990       </varlistentry>
1991
1992       <varlistentry>
1993         <term>
1994           <literal>:etags</literal> 
1995         </term>
1996         <listitem>
1997           <para>See <literal>:ctags</literal>.</para>
1998         </listitem>
1999       </varlistentry>
2000
2001       <varlistentry>
2002         <term>
2003           <literal>:force <replaceable>identifier</replaceable> ...</literal>
2004           <indexterm><primary><literal>:force</literal></primary></indexterm>
2005         </term>
2006         <listitem>
2007           <para>Prints the value of <replaceable>identifier</replaceable> in
2008             the same way as <literal>:print</literal>.   Unlike
2009             <literal>:print</literal>, <literal>:force</literal> evaluates each
2010             thunk that it encounters while traversing the value.  This may
2011             cause exceptions or infinite loops, or further breakpoints (which
2012             are ignored, but displayed).</para>
2013         </listitem>
2014       </varlistentry>
2015
2016       <varlistentry>
2017         <term>
2018           <literal>:forward</literal>
2019           <indexterm><primary><literal>:forward</literal></primary></indexterm>
2020         </term>
2021         <listitem>
2022           <para>Move forward in the history.   See <xref
2023               linkend="tracing" />.  See also:
2024             <literal>:trace</literal>, <literal>:history</literal>,
2025             <literal>:back</literal>.</para>
2026         </listitem>
2027       </varlistentry>
2028
2029       <varlistentry>
2030         <term>
2031           <literal>:help</literal>
2032           <indexterm><primary><literal>:help</literal></primary></indexterm>
2033         </term>
2034         <term>
2035           <literal>:?</literal>
2036           <indexterm><primary><literal>:?</literal></primary></indexterm>
2037         </term>
2038         <listitem>
2039           <para>Displays a list of the available commands.</para>
2040         </listitem>
2041       </varlistentry>
2042
2043       <varlistentry>
2044        <term>
2045           <literal>:</literal>
2046           <indexterm><primary><literal>:</literal></primary></indexterm>
2047         </term>
2048        <listitem>
2049          <para>Repeat the previous command.</para>
2050        </listitem>
2051       </varlistentry>
2052
2053       <varlistentry>
2054
2055         <term>
2056           <literal>:history [<replaceable>num</replaceable>]</literal>
2057           <indexterm><primary><literal>:history</literal></primary></indexterm>
2058         </term>
2059         <listitem>
2060           <para>Display the history of evaluation steps.  With a number,
2061             displays that many steps (default: 20).  For use with
2062             <literal>:trace</literal>; see <xref
2063               linkend="tracing" />.</para>
2064         </listitem>
2065       </varlistentry>
2066
2067       <varlistentry>
2068         <term>
2069           <literal>:info</literal> <replaceable>name</replaceable> ...
2070           <indexterm><primary><literal>:info</literal></primary></indexterm>
2071         </term>
2072         <listitem>
2073           <para>Displays information about the given name(s).  For
2074           example, if <replaceable>name</replaceable> is a class, then
2075           the class methods and their types will be printed;  if
2076           <replaceable>name</replaceable> is a type constructor, then
2077           its definition will be printed;  if
2078           <replaceable>name</replaceable> is a function, then its type
2079           will be printed.  If <replaceable>name</replaceable> has
2080           been loaded from a source file, then GHCi will also display
2081           the location of its definition in the source.</para>
2082           <para>For types and classes, GHCi also summarises instances that
2083           mention them.  To avoid showing irrelevant information, an instance
2084           is shown only if (a) its head mentions <replaceable>name</replaceable>, 
2085           and (b) all the other things mentioned in the instance
2086           are in scope (either qualified or otherwise) as a result of 
2087           a <literal>:load</literal> or <literal>:module</literal> commands. </para>
2088         </listitem>
2089       </varlistentry>
2090
2091       <varlistentry>
2092         <term>
2093           <literal>:kind</literal> <replaceable>type</replaceable>
2094           <indexterm><primary><literal>:kind</literal></primary></indexterm>
2095         </term>
2096         <listitem>
2097           <para>Infers and prints the kind of
2098           <replaceable>type</replaceable>. The latter can be an arbitrary
2099             type expression, including a partial application of a type constructor,
2100             such as <literal>Either Int</literal>.</para>
2101         </listitem>
2102       </varlistentry>
2103
2104       <varlistentry>
2105         <term>
2106           <literal>:load</literal> <replaceable>module</replaceable> ...
2107           <indexterm><primary><literal>:load</literal></primary></indexterm>
2108         </term>
2109         <listitem>
2110           <para>Recursively loads the specified
2111           <replaceable>module</replaceable>s, and all the modules they
2112           depend on.  Here, each <replaceable>module</replaceable>
2113           must be a module name or filename, but may not be the name
2114           of a module in a package.</para>
2115
2116           <para>All previously loaded modules, except package modules,
2117           are forgotten.  The new set of modules is known as the
2118           <firstterm>target set</firstterm>.  Note that
2119           <literal>:load</literal> can be used without any arguments
2120           to unload all the currently loaded modules and
2121           bindings.</para>
2122
2123           <para>After a <literal>:load</literal> command, the current
2124           context is set to:</para>
2125
2126           <itemizedlist>
2127             <listitem>
2128               <para><replaceable>module</replaceable>, if it was loaded
2129               successfully, or</para>
2130             </listitem>
2131             <listitem>
2132               <para>the most recently successfully loaded module, if
2133               any other modules were loaded as a result of the current
2134               <literal>:load</literal>, or</para>
2135             </listitem>
2136             <listitem>
2137               <para><literal>Prelude</literal> otherwise.</para>
2138             </listitem>
2139           </itemizedlist>
2140         </listitem>
2141       </varlistentry>
2142
2143       <varlistentry>
2144         <term>
2145           <literal>:main <replaceable>arg<subscript>1</subscript></replaceable> ... <replaceable>arg<subscript>n</subscript></replaceable></literal>
2146           <indexterm><primary><literal>:main</literal></primary></indexterm>
2147         </term>
2148         <listitem>
2149           <para>
2150             When a program is compiled and executed, it can use the
2151             <literal>getArgs</literal> function to access the
2152             command-line arguments.
2153             However, we cannot simply pass the arguments to the
2154             <literal>main</literal> function while we are testing in ghci,
2155             as the <literal>main</literal> function doesn't take its
2156             arguments directly.
2157           </para>
2158
2159           <para>
2160             Instead, we can use the <literal>:main</literal> command.
2161             This runs whatever <literal>main</literal> is in scope, with
2162             any arguments being treated the same as command-line arguments,
2163             e.g.:
2164           </para>
2165
2166 <screen>
2167 Prelude> let main = System.Environment.getArgs >>= print
2168 Prelude> :main foo bar
2169 ["foo","bar"]
2170 </screen>
2171
2172         <para>
2173             We can also quote arguments which contains characters like
2174             spaces, and they are treated like Haskell strings, or we can
2175             just use Haskell list syntax:
2176         </para>
2177
2178 <screen>
2179 Prelude> :main foo "bar baz"
2180 ["foo","bar baz"]
2181 Prelude> :main ["foo", "bar baz"]
2182 ["foo","bar baz"]
2183 </screen>
2184
2185         <para>
2186             Finally, other functions can be called, either with the
2187             <literal>-main-is</literal> flag or the <literal>:run</literal>
2188             command:
2189         </para>
2190
2191 <screen>
2192 Prelude> let foo = putStrLn "foo" >> System.Environment.getArgs >>= print
2193 Prelude> let bar = putStrLn "bar" >> System.Environment.getArgs >>= print
2194 Prelude> :set -main-is foo
2195 Prelude> :main foo "bar baz"
2196 foo
2197 ["foo","bar baz"]
2198 Prelude> :run bar ["foo", "bar baz"]
2199 bar
2200 ["foo","bar baz"]
2201 </screen>
2202
2203         </listitem>
2204       </varlistentry>
2205
2206       <varlistentry>
2207         <term>
2208           <literal>:module <optional>+|-</optional> <optional>*</optional><replaceable>mod<subscript>1</subscript></replaceable> ... <optional>*</optional><replaceable>mod<subscript>n</subscript></replaceable></literal>
2209           <indexterm><primary><literal>:module</literal></primary></indexterm>
2210         </term>
2211         <term>
2212           <literal>import <replaceable>mod</replaceable></literal>
2213         </term>
2214         <listitem>
2215           <para>Sets or modifies the current context for statements
2216           typed at the prompt.  The form <literal>import
2217           <replaceable>mod</replaceable></literal> is equivalent to
2218           <literal>:module +<replaceable>mod</replaceable></literal>.
2219           See <xref linkend="ghci-scope"/> for
2220           more details.</para>
2221         </listitem>
2222       </varlistentry>
2223
2224       <varlistentry>
2225         <term>
2226           <literal>:print </literal> <replaceable>names</replaceable> ...
2227           <indexterm><primary><literal>:print</literal></primary></indexterm>
2228         </term>
2229         <listitem>
2230           <para>Prints a value without forcing its evaluation.
2231             <literal>:print</literal> may be used on values whose types are
2232             unknown or partially known, which might be the case for local
2233             variables with polymorphic types at a breakpoint.  While inspecting
2234             the runtime value, <literal>:print</literal> attempts to
2235             reconstruct the type of the value, and will elaborate the type in
2236             GHCi's environment if possible.  If any unevaluated components
2237             (thunks) are encountered, then <literal>:print</literal> binds
2238             a fresh variable with a name beginning with <literal>_t</literal>
2239             to each thunk.  See <xref linkend="breakpoints" /> for more
2240             information.  See also the <literal>:sprint</literal> command,
2241             which works like <literal>:print</literal> but does not bind new
2242             variables.</para>
2243         </listitem>
2244       </varlistentry>
2245
2246       <varlistentry>
2247         <term>
2248           <literal>:quit</literal>
2249           <indexterm><primary><literal>:quit</literal></primary></indexterm>
2250         </term>
2251         <listitem>
2252           <para>Quits GHCi.  You can also quit by typing control-D
2253           at the prompt.</para>
2254         </listitem>
2255       </varlistentry>
2256
2257       <varlistentry>
2258         <term>
2259           <literal>:reload</literal>
2260           <indexterm><primary><literal>:reload</literal></primary></indexterm>
2261         </term>
2262         <listitem>
2263           <para>Attempts to reload the current target set (see
2264           <literal>:load</literal>) if any of the modules in the set,
2265           or any dependent module, has changed.  Note that this may
2266           entail loading new modules, or dropping modules which are no
2267           longer indirectly required by the target.</para>
2268         </listitem>
2269       </varlistentry>
2270
2271       <varlistentry>
2272         <term>
2273           <literal>:set</literal> <optional><replaceable>option</replaceable>...</optional>
2274           <indexterm><primary><literal>:set</literal></primary></indexterm>
2275         </term>
2276         <listitem>
2277     <para>Sets various options.  See <xref linkend="ghci-set"/> for a list of
2278       available options and <xref linkend="interactive-mode-options"/> for a
2279       list of GHCi-specific flags.  The <literal>:set</literal> command by
2280       itself shows which options are currently set. It also lists the current
2281       dynamic flag settings, with GHCi-specific flags listed separately.</para>
2282         </listitem>
2283       </varlistentry>
2284
2285       <varlistentry>
2286         <term>
2287           <literal>:set</literal> <literal>args</literal> <replaceable>arg</replaceable> ...
2288           <indexterm><primary><literal>:set args</literal></primary></indexterm>
2289         </term>
2290         <listitem>
2291           <para>Sets the list of arguments which are returned when the
2292           program calls <literal>System.getArgs</literal><indexterm><primary>getArgs</primary>
2293             </indexterm>.</para>
2294         </listitem>
2295       </varlistentry>
2296
2297       <varlistentry>
2298         <term>
2299            <literal>:set</literal> <literal>editor</literal> <replaceable>cmd</replaceable>
2300         </term>
2301         <listitem>
2302           <para>Sets the command used by <literal>:edit</literal> to
2303           <replaceable>cmd</replaceable>.</para>
2304         </listitem>
2305       </varlistentry>
2306
2307       <varlistentry>
2308         <term>
2309            <literal>:set</literal> <literal>prog</literal> <replaceable>prog</replaceable>
2310            <indexterm><primary><literal>:set prog</literal></primary></indexterm>
2311         </term>
2312         <listitem>
2313           <para>Sets the string to be returned when the program calls
2314           <literal>System.getProgName</literal><indexterm><primary>getProgName</primary>
2315             </indexterm>.</para>
2316         </listitem>
2317       </varlistentry>
2318
2319       <varlistentry>
2320         <term>
2321            <literal>:set</literal> <literal>prompt</literal> <replaceable>prompt</replaceable>
2322         </term>
2323         <listitem>
2324           <para>Sets the string to be used as the prompt in GHCi.
2325           Inside <replaceable>prompt</replaceable>, the sequence
2326           <literal>%s</literal> is replaced by the names of the
2327           modules currently in scope, and <literal>%%</literal> is
2328           replaced by <literal>%</literal>.</para>
2329         </listitem>
2330       </varlistentry>
2331
2332       <varlistentry>
2333         <term>
2334            <literal>:set</literal> <literal>stop</literal>
2335           [<replaceable>num</replaceable>] <replaceable>cmd</replaceable>
2336         </term>
2337         <listitem>
2338           <para>Set a command to be executed when a breakpoint is hit, or a new
2339           item in the history is selected.  The most common use of
2340             <literal>:set stop</literal> is to display the source code at the
2341             current location, e.g. <literal>:set stop :list</literal>.</para>
2342
2343           <para>If a number is given before the command, then the commands are
2344             run when the specified breakpoint (only) is hit.  This can be quite
2345             useful: for example, <literal>:set stop 1 :continue</literal>
2346             effectively disables breakpoint 1, by running
2347             <literal>:continue</literal> whenever it is hit (although GHCi will
2348             still emit a message to say the breakpoint was hit).  What's more,
2349             with cunning use of <literal>:def</literal> and
2350             <literal>:cmd</literal> you can use <literal>:set stop</literal> to
2351             implement conditional breakpoints:</para>
2352 <screen>
2353 *Main> :def cond \expr -> return (":cmd if (" ++ expr ++ ") then return \"\" else return \":continue\"")
2354 *Main> :set stop 0 :cond (x &lt; 3)
2355 </screen>
2356           <para>Ignoring breakpoints for a specified number of iterations is
2357             also possible using similar techniques.</para>
2358         </listitem>
2359       </varlistentry>
2360
2361       <varlistentry>
2362         <term>
2363           <literal>:show bindings</literal>
2364           <indexterm><primary><literal>:show bindings</literal></primary></indexterm>
2365         </term>
2366         <listitem>
2367           <para>Show the bindings made at the prompt and their
2368           types.</para>
2369         </listitem>
2370       </varlistentry>
2371
2372       <varlistentry>
2373         <term>
2374           <literal>:show breaks</literal>
2375           <indexterm><primary><literal>:show breaks</literal></primary></indexterm>
2376         </term>
2377         <listitem>
2378           <para>List the active breakpoints.</para>
2379         </listitem>
2380       </varlistentry>
2381
2382       <varlistentry>
2383         <term>
2384           <literal>:show context</literal>
2385           <indexterm><primary><literal>:show context</literal></primary></indexterm>
2386         </term>
2387         <listitem>
2388           <para>List the active evaluations that are stopped at breakpoints.</para>
2389         </listitem>
2390       </varlistentry>
2391
2392       <varlistentry>
2393         <term>
2394           <literal>:show modules</literal>
2395           <indexterm><primary><literal>:show modules</literal></primary></indexterm>
2396         </term>
2397         <listitem>
2398           <para>Show the list of modules currently loaded.</para>
2399         </listitem>
2400       </varlistentry>
2401
2402       <varlistentry>
2403         <term>
2404           <literal>:show packages</literal>
2405           <indexterm><primary><literal>:show packages</literal></primary></indexterm>
2406         </term>
2407         <listitem>
2408     <para>Show the currently active package flags, as well as the list of
2409       packages currently loaded.</para>
2410         </listitem>
2411       </varlistentry>
2412
2413       <varlistentry>
2414         <term>
2415           <literal>:show languages</literal>
2416           <indexterm><primary><literal>:show languages</literal></primary></indexterm>
2417         </term>
2418         <listitem>
2419     <para>Show the currently active language flags.</para>
2420         </listitem>
2421       </varlistentry>
2422
2423
2424       <varlistentry>
2425         <term>
2426           <literal>:show [args|prog|prompt|editor|stop]</literal>
2427           <indexterm><primary><literal>:show</literal></primary></indexterm>
2428         </term>
2429         <listitem>
2430           <para>Displays the specified setting (see
2431             <literal>:set</literal>).</para>
2432         </listitem>
2433       </varlistentry>
2434
2435       <varlistentry>
2436         <term>
2437           <literal>:sprint</literal>
2438           <indexterm><primary><literal>:sprint</literal></primary></indexterm>
2439         </term>
2440         <listitem>
2441           <para>Prints a value without forcing its evaluation.
2442             <literal>:sprint</literal> is similar to <literal>:print</literal>,
2443             with the difference that unevaluated subterms are not bound to new
2444             variables, they are simply denoted by &lsquo;_&rsquo;.</para>
2445         </listitem>
2446       </varlistentry>
2447
2448       <varlistentry>
2449         <term>
2450           <literal>:step [<replaceable>expr</replaceable>]</literal> 
2451           <indexterm><primary><literal>:step</literal></primary></indexterm>
2452         </term>
2453         <listitem>
2454           <para>Single-step from the last breakpoint.  With an expression
2455             argument, begins evaluation of the expression with a
2456             single-step.</para>
2457         </listitem>
2458       </varlistentry>
2459
2460       <varlistentry>
2461         <term>
2462           <literal>:trace [<replaceable>expr</replaceable>]</literal>
2463           <indexterm><primary><literal>:trace</literal></primary></indexterm>
2464         </term>
2465         <listitem>
2466           <para>Evaluates the given expression (or from the last breakpoint if
2467             no expression is given), and additionally logs the evaluation
2468             steps for later inspection using <literal>:history</literal>.  See
2469             <xref linkend="tracing" />.</para>
2470         </listitem>
2471       </varlistentry>
2472
2473       <varlistentry>
2474         <term>
2475          <literal>:type</literal> <replaceable>expression</replaceable>
2476          <indexterm><primary><literal>:type</literal></primary></indexterm>
2477         </term>
2478         <listitem>
2479           <para>Infers and prints the type of
2480           <replaceable>expression</replaceable>, including explicit
2481           forall quantifiers for polymorphic types.  The monomorphism
2482           restriction is <emphasis>not</emphasis> applied to the
2483           expression during type inference.</para>
2484         </listitem>
2485       </varlistentry>
2486
2487       <varlistentry>
2488         <term>
2489           <literal>:undef</literal> <replaceable>name</replaceable>
2490           <indexterm><primary><literal>:undef</literal></primary></indexterm>
2491         </term>
2492         <listitem>
2493           <para>Undefines the user-defined command
2494           <replaceable>name</replaceable> (see <literal>:def</literal>
2495           above).</para>
2496         </listitem>
2497       </varlistentry>
2498
2499       <varlistentry>
2500         <term>
2501           <literal>:unset</literal> <replaceable>option</replaceable>...
2502           <indexterm><primary><literal>:unset</literal></primary></indexterm>
2503         </term>
2504         <listitem>
2505           <para>Unsets certain options.  See <xref linkend="ghci-set"/>
2506           for a list of available options.</para>
2507         </listitem>
2508       </varlistentry>
2509
2510       <varlistentry>
2511         <term>
2512           <literal>:!</literal> <replaceable>command</replaceable>...
2513           <indexterm><primary><literal>:!</literal></primary></indexterm>
2514           <indexterm><primary>shell commands</primary><secondary>in GHCi</secondary></indexterm>
2515         </term>
2516         <listitem>
2517           <para>Executes the shell command
2518           <replaceable>command</replaceable>.</para>
2519         </listitem>
2520       </varlistentry>
2521
2522     </variablelist>
2523   </sect1>
2524
2525   <sect1 id="ghci-set">
2526     <title>The <literal>:set</literal> command</title>
2527     <indexterm><primary><literal>:set</literal></primary></indexterm>
2528
2529     <para>The <literal>:set</literal> command sets two types of
2530     options: GHCi options, which begin with
2531     &lsquo;<literal>+</literal>&rsquo;, and &ldquo;command-line&rdquo;
2532     options, which begin with &lsquo;-&rsquo;.  </para>
2533
2534     <para>NOTE: at the moment, the <literal>:set</literal> command
2535     doesn't support any kind of quoting in its arguments: quotes will
2536     not be removed and cannot be used to group words together.  For
2537     example, <literal>:set -DFOO='BAR BAZ'</literal> will not do what
2538     you expect.</para>
2539
2540     <sect2>
2541       <title>GHCi options</title>
2542       <indexterm><primary>options</primary><secondary>GHCi</secondary>
2543       </indexterm>
2544
2545       <para>GHCi options may be set using <literal>:set</literal> and
2546       unset using <literal>:unset</literal>.</para>
2547
2548       <para>The available GHCi options are:</para>
2549
2550       <variablelist>
2551         <varlistentry>
2552           <term>
2553             <literal>+r</literal>
2554             <indexterm><primary><literal>+r</literal></primary></indexterm>
2555             <indexterm><primary>CAFs</primary><secondary>in GHCi</secondary></indexterm>
2556             <indexterm><primary>Constant Applicative Form</primary><see>CAFs</see></indexterm>
2557           </term>
2558           <listitem>
2559             <para>Normally, any evaluation of top-level expressions
2560             (otherwise known as CAFs or Constant Applicative Forms) in
2561             loaded modules is retained between evaluations.  Turning
2562             on <literal>+r</literal> causes all evaluation of
2563             top-level expressions to be discarded after each
2564             evaluation (they are still retained
2565             <emphasis>during</emphasis> a single evaluation).</para>
2566           
2567             <para>This option may help if the evaluated top-level
2568             expressions are consuming large amounts of space, or if
2569             you need repeatable performance measurements.</para>
2570           </listitem>
2571         </varlistentry>
2572
2573         <varlistentry>
2574           <term>
2575             <literal>+s</literal>
2576             <indexterm><primary><literal>+s</literal></primary></indexterm>
2577           </term>
2578           <listitem>
2579             <para>Display some stats after evaluating each expression,
2580             including the elapsed time and number of bytes allocated.
2581             NOTE: the allocation figure is only accurate to the size
2582             of the storage manager's allocation area, because it is
2583             calculated at every GC.  Hence, you might see values of
2584             zero if no GC has occurred.</para>
2585           </listitem>
2586         </varlistentry>
2587
2588         <varlistentry>
2589           <term>
2590             <literal>+t</literal>
2591             <indexterm><primary><literal>+t</literal></primary></indexterm>
2592           </term>
2593           <listitem>
2594             <para>Display the type of each variable bound after a
2595             statement is entered at the prompt.  If the statement is a
2596             single expression, then the only variable binding will be
2597             for the variable
2598             &lsquo;<literal>it</literal>&rsquo;.</para>
2599           </listitem>
2600         </varlistentry>
2601       </variablelist>
2602     </sect2>
2603
2604     <sect2 id="ghci-cmd-line-options">
2605       <title>Setting GHC command-line options in GHCi</title>
2606
2607       <para>Normal GHC command-line options may also be set using
2608       <literal>:set</literal>.  For example, to turn on
2609       <option>-fglasgow-exts</option>, you would say:</para>
2610
2611 <screen>
2612 Prelude> :set -fglasgow-exts
2613 </screen>
2614       
2615       <para>Any GHC command-line option that is designated as
2616       <firstterm>dynamic</firstterm> (see the table in <xref
2617       linkend="flag-reference"/>), may be set using
2618       <literal>:set</literal>.  To unset an option, you can set the
2619       reverse option:</para>
2620       <indexterm><primary>dynamic</primary><secondary>options</secondary></indexterm>
2621
2622 <screen>
2623 Prelude> :set -fno-glasgow-exts
2624 </screen>
2625
2626       <para><xref linkend="flag-reference"/> lists the reverse for each
2627       option where applicable.</para>
2628
2629       <para>Certain static options (<option>-package</option>,
2630       <option>-I</option>, <option>-i</option>, and
2631       <option>-l</option> in particular) will also work, but some may
2632       not take effect until the next reload.</para>
2633       <indexterm><primary>static</primary><secondary>options</secondary></indexterm>
2634     </sect2>
2635   </sect1>
2636   <sect1 id="ghci-dot-files">
2637     <title>The <filename>.ghci</filename> file</title>
2638     <indexterm><primary><filename>.ghci</filename></primary><secondary>file</secondary>
2639     </indexterm>
2640     <indexterm><primary>startup</primary><secondary>files, GHCi</secondary>
2641     </indexterm>
2642
2643     <para>When it starts, unless the <literal>-ignore-dot-ghci</literal>
2644     flag is given, GHCi reads and executes commands from the following
2645     files, in this order, if they exist:</para>
2646
2647     <orderedlist>
2648     <listitem>
2649       <para><filename>./.ghci</filename></para>
2650     </listitem>
2651     <listitem>
2652       <para><literal><replaceable>appdata</replaceable>/ghc/ghci.conf</literal>,
2653       where <replaceable>appdata</replaceable> depends on your system,
2654       but is usually something like <literal>C:/Documents and Settings/<replaceable>user</replaceable>/Application Data</literal></para>
2655     </listitem>
2656     <listitem>
2657       <para>On Unix: <literal>$HOME/.ghc/ghci.conf</literal></para>
2658     </listitem>
2659     <listitem>
2660       <para><literal>$HOME/.ghci</literal></para>
2661     </listitem>
2662    </orderedlist>
2663
2664     <para>The <filename>ghci.conf</filename> file is most useful for
2665     turning on favourite options (eg. <literal>:set +s</literal>), and
2666     defining useful macros.  Placing a <filename>.ghci</filename> file
2667     in a directory with a Haskell project is a useful way to set
2668     certain project-wide options so you don't have to type them
2669     everytime you start GHCi: eg. if your project uses GHC extensions
2670     and CPP, and has source files in three subdirectories A, B and C,
2671     you might put the following lines in
2672     <filename>.ghci</filename>:</para>
2673
2674 <screen>
2675 :set -fglasgow-exts -cpp
2676 :set -iA:B:C
2677 </screen>
2678
2679     <para>(Note that strictly speaking the <option>-i</option> flag is
2680     a static one, but in fact it works to set it using
2681     <literal>:set</literal> like this.  The changes won't take effect
2682     until the next <literal>:load</literal>, though.)</para>
2683
2684     <para>Once you have a library of GHCi macros, you may want
2685     to source them from separate files, or you may want to source
2686     your <filename>.ghci</filename> file into your running GHCi
2687     session while debugging it</para>
2688
2689 <screen>
2690 :def source readFile
2691 </screen>
2692
2693     <para>With this macro defined in your <filename>.ghci</filename> 
2694     file, you can use <literal>:source file</literal> to read GHCi
2695     commands from <literal>file</literal>. You can find (and contribute!-)
2696     other suggestions for <filename>.ghci</filename> files on this Haskell
2697     wiki page: <ulink
2698       url="http://haskell.org/haskellwiki/GHC/GHCi">GHC/GHCi</ulink></para>
2699
2700     <para>Two command-line options control whether the
2701     startup files files are read:</para>
2702
2703     <variablelist>
2704       <varlistentry>
2705         <term>
2706           <option>-ignore-dot-ghci</option>
2707           <indexterm><primary><option>-ignore-dot-ghci</option></primary></indexterm>
2708         </term>
2709         <listitem>
2710           <para>Don't read either <filename>./.ghci</filename> or the
2711           other startup files when starting up.</para>
2712         </listitem>
2713       </varlistentry>
2714       <varlistentry>
2715         <term>
2716           <option>-read-dot-ghci</option>
2717           <indexterm><primary><option>-read-dot-ghci</option></primary></indexterm>
2718         </term>
2719         <listitem>
2720           <para>Read <filename>./.ghci</filename> and the other
2721           startup files (see above).  This is normally the
2722           default, but the <option>-read-dot-ghci</option> option may
2723           be used to override a previous
2724           <option>-ignore-dot-ghci</option> option.</para>
2725         </listitem>
2726       </varlistentry>
2727     </variablelist>
2728
2729   </sect1>
2730
2731   <sect1 id="ghci-obj">
2732     <title>Compiling to object code inside GHCi</title>
2733
2734     <para>By default, GHCi compiles Haskell source code into byte-code
2735     that is interpreted by the runtime system.  GHCi can also compile
2736     Haskell code to object code: to turn on this feature, use the
2737     <option>-fobject-code</option> flag either on the command line or
2738     with <literal>:set</literal> (the option
2739     <option>-fbyte-code</option> restores byte-code compilation
2740     again).  Compiling to object code takes longer, but typically the
2741     code will execute 10-20 times faster than byte-code.</para>
2742
2743     <para>Compiling to object code inside GHCi is particularly useful
2744     if you are developing a compiled application, because the
2745     <literal>:reload</literal> command typically runs much faster than
2746     restarting GHC with <option>--make</option> from the command-line,
2747     because all the interface files are already cached in
2748     memory.</para>
2749
2750     <para>There are disadvantages to compiling to object-code: you
2751     can't set breakpoints in object-code modules, for example.  Only
2752     the exports of an object-code module will be visible in GHCi,
2753     rather than all top-level bindings as in interpreted
2754     modules.</para>
2755   </sect1>
2756
2757   <sect1 id="ghci-faq">
2758     <title>FAQ and Things To Watch Out For</title>
2759     
2760     <variablelist>
2761       <varlistentry>
2762         <term>The interpreter can't load modules with foreign export
2763         declarations!</term>
2764         <listitem>
2765           <para>Unfortunately not.  We haven't implemented it yet.
2766           Please compile any offending modules by hand before loading
2767           them into GHCi.</para>
2768         </listitem>
2769       </varlistentry>
2770
2771       <varlistentry>
2772         <term>
2773           <literal>-O</literal> doesn't work with GHCi!
2774           <indexterm><primary><option>-O</option></primary></indexterm>
2775          </term>
2776         <listitem>
2777           <para>For technical reasons, the bytecode compiler doesn't
2778           interact well with one of the optimisation passes, so we
2779           have disabled optimisation when using the interpreter.  This
2780           isn't a great loss: you'll get a much bigger win by
2781           compiling the bits of your code that need to go fast, rather
2782           than interpreting them with optimisation turned on.</para>
2783         </listitem>
2784       </varlistentry>
2785
2786       <varlistentry>
2787         <term>Unboxed tuples don't work with GHCi</term>
2788         <listitem>
2789           <para>That's right.  You can always compile a module that
2790           uses unboxed tuples and load it into GHCi, however.
2791           (Incidentally the previous point, namely that
2792           <literal>-O</literal> is incompatible with GHCi, is because
2793           the bytecode compiler can't deal with unboxed
2794           tuples).</para>
2795         </listitem>
2796       </varlistentry>
2797
2798       <varlistentry>
2799         <term>Concurrent threads don't carry on running when GHCi is
2800         waiting for input.</term>
2801         <listitem>
2802           <para>This should work, as long as your GHCi was built with
2803           the <option>-threaded</option> switch, which is the default.
2804           Consult whoever supplied your GHCi installation.</para>
2805         </listitem>
2806       </varlistentry>
2807
2808       <varlistentry>
2809         <term>After using <literal>getContents</literal>, I can't use
2810         <literal>stdin</literal> again until I do
2811         <literal>:load</literal> or <literal>:reload</literal>.</term>
2812
2813         <listitem>
2814           <para>This is the defined behaviour of
2815           <literal>getContents</literal>: it puts the stdin Handle in
2816           a state known as <firstterm>semi-closed</firstterm>, wherein
2817           any further I/O operations on it are forbidden.  Because I/O
2818           state is retained between computations, the semi-closed
2819           state persists until the next <literal>:load</literal> or
2820           <literal>:reload</literal> command.</para>
2821
2822           <para>You can make <literal>stdin</literal> reset itself
2823           after every evaluation by giving GHCi the command
2824           <literal>:set +r</literal>.  This works because
2825           <literal>stdin</literal> is just a top-level expression that
2826           can be reverted to its unevaluated state in the same way as
2827           any other top-level expression (CAF).</para>
2828         </listitem>
2829       </varlistentry>
2830
2831       <varlistentry>
2832         <term>I can't use Control-C to interrupt computations in
2833           GHCi on Windows.</term>
2834         <listitem>
2835           <para>See <xref linkend="ghci-windows"/>.</para>
2836         </listitem>
2837       </varlistentry>
2838
2839       <varlistentry>
2840         <term>The default buffering mode is different in GHCi to GHC.</term>
2841         <listitem>
2842           <para>
2843             In GHC, the stdout handle is line-buffered by default.
2844             However, in GHCi we turn off the buffering on stdout,
2845             because this is normally what you want in an interpreter:
2846             output appears as it is generated.
2847           </para>
2848         </listitem>
2849       </varlistentry>
2850     </variablelist>
2851   </sect1>
2852
2853 </chapter>
2854
2855 <!-- Emacs stuff:
2856      ;;; Local Variables: ***
2857      ;;; mode: xml ***
2858      ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") ***
2859      ;;; End: ***
2860  -->