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