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