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