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