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