[project @ 2001-10-22 10:33:50 by simonmar]
[ghc-hetmet.git] / ghc / docs / users_guide / ghci.sgml
1 <chapter id="ghci">
2   <title>Using GHCi</title>
3   <indexterm><primary>GHCi</primary></indexterm>
4   <indexterm><primary>interpreter</primary><see>GHCi</see></indexterm>
5   <indexterm><primary>interactive</primary><see>GHCi</see></indexterm>
6   
7   <para>GHCi<footnote>
8       <para>The &lsquo;i&rsquo; stands for &ldquo;Interactive&rdquo;</para>
9     </footnote>
10   is GHC's interactive environment, in which Haskell expressions can
11   be interactively evaluated and programs can be interpreted.  If
12   you're famililar with Hugs<indexterm><primary>Hugs</primary>
13   </indexterm>, then you'll be right at home with GHCi.  However, GHCi
14   also has support for interactively loading compiled code, as well as
15   supporting all<footnote><para>except <literal>foreign export</literal>, at the moment</para>
16   </footnote>the language extensions that GHC provides.</para>
17   <indexterm><primary>FFI</primary><secondary>GHCi support</secondary></indexterm>
18   <indexterm><primary>Foreign Function Interface</primary><secondary>GHCi support</secondary></indexterm>
19
20   <sect1>
21     <title>Introduction to GHCi</title>
22
23     <para>Let's start with an example GHCi session.  You can fire up
24     GHCi with the command <literal>ghci</literal>:</para>
25
26 <screen>
27 $ ghci
28    ___         ___ _
29   / _ \ /\  /\/ __(_)
30  / /_\// /_/ / /  | |      GHC Interactive, version 5.00, For Haskell 98.
31 / /_\\/ __  / /___| |      http://www.haskell.org/ghc/
32 \____/\/ /_/\____/|_|      Type :? for help.
33
34 Loading package std ... linking ... done.
35 Prelude> 
36 </screen>
37
38     <para>There may be a short pause while GHCi loads the prelude and
39     standard libraries, after which the prompt is shown.  If we follow
40     the instructions and type <literal>:?</literal> for help, we
41     get:</para>
42
43 <screen>
44  Commands available from the prompt:
45    &lt;stmt&gt;              evaluate/run &lt;stmt&gt;
46    :cd &lt;dir&gt;           change directory to &lt;dir&gt;
47    :def &lt;cmd&gt; &lt;expr&gt;   define a macro :&lt;cmd&gt;
48    :help, :?           display this list of commands
49    :load &lt;filename&gt;    load a module (and it dependents)
50    :module &lt;mod&gt;       set the context for expression evaluation to &lt;mod&gt;
51    :reload             reload the current module set
52    :set &lt;option&gt; ...   set options
53    :type &lt;expr&gt;        show the type of &lt;expr&gt;
54    :unset &lt;option&gt; ... unset options
55    :quit               exit GHCi
56    :!&lt;command&gt;         run the shell command &lt;command&gt;
57  Options for `:set' and `:unset':
58     +r                 revert top-level expressions after each evaluation
59     +s                 print timing/memory stats after each evaluation
60     +t                 print type after evaluation
61     -&lt;flag&gt;            most GHC command line flags can also be set here
62                          (eg. -v2, -fglasgow-exts, etc.)
63 </screen>
64
65     <para>We'll explain most of these commands as we go along.  For
66     Hugs users: many things work the same as in Hugs, so you should be
67     able to get going straight away.</para>
68
69     <para>Haskell expressions can be typed at the prompt:</para>
70     <indexterm><primary>prompt</primary><secondary>GHCi</secondary>
71   </indexterm>
72
73 <screen>
74 Prelude> 1+2
75 3
76 Prelude> let x = 42 in x / 9
77 4.666666666666667
78 Prelude> 
79 </screen>
80
81     <para>GHCi interprets the whole line as an expression to evaluate.
82     The expression may not span several lines - as soon as you press
83     enter, GHCi will attempt to evaluate it.</para>
84   </sect1>
85
86   <sect1>
87     <title>Loading source files</title>
88
89     <para>Suppose we have the following Haskell source code, which we
90     place in a file <filename>Main.hs</filename> in the current
91     directory:</para>
92
93 <programlisting>
94 main = print (fac 20)
95
96 fac 0 = 1
97 fac n = n * fac (n-1)
98 </programlisting>
99
100     <para>To load a Haskell source file into GHCi, use the
101     <literal>:load</literal> command:</para>
102     <indexterm><primary><literal>:load</literal></primary></indexterm>
103
104 <screen>
105 Prelude> :load Main
106 Compiling Main             ( Main.hs, interpreted )
107 Ok, modules loaded: Main.
108 Main>
109 </screen>
110
111     <para>GHCi has loaded the <literal>Main</literal> module, and the
112     prompt has changed to &ldquo;<literal>Main></literal>&rdquo; to
113     indicate that the current context for expressions typed at the
114     prompt is the <literal>Main</literal> module we just
115     loaded.  So we can now type expressions involving the functions
116     from <filename>Main.hs</filename>:</para>
117
118 <screen>
119 Main> fac 17
120 355687428096000
121 </screen>
122
123     <para>Loading a multi-module program is just as straightforward;
124     just give the name of the &ldquo;topmost&rdquo; module to the
125     <literal>:load</literal> command (hint: <literal>:load</literal>
126     can be abbreviated to <literal>:l</literal>).  The topmost module
127     will normally be <literal>Main</literal>, but it doesn't have to
128     be.  GHCi will discover which modules are required, directly or
129     indirectly, by the topmost module, and load them all in dependency
130     order.</para>
131
132     <sect2>
133       <title>Modules vs. filenames</title>
134       <indexterm><primary>modules</primary><secondary>and filenames</secondary></indexterm>
135       <indexterm><primary>filenames</primary><secondary>of modules</secondary></indexterm>
136       
137       <para>Question: How does GHC find the filename which contains
138       module <replaceable>M</replaceable>?  Answer: it looks for the
139       file <literal><replaceable>M</replaceable>.hs</literal>, or
140       <literal><replaceable>M</replaceable>.lhs</literal>.  This means
141       that for most modules, the module name must match the filename.
142       If it doesn't, GHCi won't be able to find it.</para>
143
144       <para>There is one exception to this general rule: when you load
145       a program with <literal>:load</literal>, or specify it when you
146       invoke <literal>ghci</literal>, you can give a filename rather
147       than a module name.  This filename is loaded if it exists, and
148       it may contain any module you like.  This is particularly
149       convenient if you have several <literal>Main</literal> modules
150       in the same directory and you can't call them all
151       <filename>Main.hs</filename>.</para>
152
153       <para>One consequence of the way that GHCi follows dependencies
154       to find modules to load is that every module must have a source
155       file.  The only exception to the rule is modules that come from
156       a package, including the <literal>Prelude</literal> and standard
157       libraries such as <literal>IO</literal> and
158       <literal>Complex</literal>.  If you attempt to load a module for
159       which GHCi can't find a source file, even if there are object
160       and interface files for the module, you'll get an error
161       message.</para>
162
163       <para>One final note: if you load a module called Main, it must
164       contain a <literal>main</literal> function, just like in
165       GHC.</para>
166     </sect2>
167
168     <sect2>
169       <title>Making changes and recompilation</title>
170       <indexterm><primary><literal>:reload</literal></primary></indexterm>
171
172       <para>If you make some changes to the source code and want GHCi
173       to recompile the program, give the <literal>:reload</literal>
174       command.  The program will be recompiled as necessary, with GHCi
175       doing its best to avoid actually recompiling modules if their
176       external dependencies haven't changed.  This is the same
177       mechanism we use to avoid re-compiling modules in the batch
178       compilation setting (see <xref linkend="recomp">).</para>
179     </sect2>
180   </sect1>
181
182   <sect1 id="ghci-compiled">
183     <title>Loading compiled code</title>
184     <indexterm><primary>compiled code</primary><secondary>in GHCi</secondary></indexterm>
185
186     <para>When you load a Haskell source module into GHCi, it is
187     normally converted to byte-code and run using the interpreter.
188     However, interpreted code can also run alongside compiled code in
189     GHCi; indeed, normally when GHCi starts, it loads up a compiled
190     copy of package <literal>std</literal>, which contains the Prelude
191     and standard libraries.</para>
192
193     <para>Why should we want to run compiled code?  Well, compiled
194     code is roughly 10x faster than interpreted code, but takes about
195     2x longer to produce (perhaps longer if optimisation is on).  So
196     it pays to compile the parts of a program that aren't changing
197     very often, and use the interpreter for the code being actively
198     developed.</para>
199
200     <para>When loading up source files with <literal>:load</literal>,
201     GHCi looks for any corresponding compiled object files, and will
202     use one in preference to interpreting the source if possible.  For
203     example, suppose we have a 4-module program consisting of modules
204     A, B, C, and D.  Modules B and C both import D only,
205     and A imports both B & C:</para>
206 <screen>
207       A
208      / \
209     B   C
210      \ /
211       D
212 </screen>
213     <para>We can compile D, then load the whole program, like this:</para>
214 <screen>
215 Prelude> :! ghc -c D.hs
216 Prelude> :load A
217 Skipping  D                ( D.hs, D.o )
218 Compiling C                ( C.hs, interpreted )
219 Compiling B                ( B.hs, interpreted )
220 Compiling A                ( A.hs, interpreted )
221 Ok, modules loaded: A, B, C, D.
222 Main>
223 </screen>
224
225     <para>In the messages from the compiler, we see that it skipped D,
226     and used the object file <filename>D.o</filename>.  The message
227     <literal>Skipping</literal> <replaceable>module</replaceable>
228     indicates that compilation for <replaceable>module</replaceable>
229     isn't necessary, because the source and everything it depends on
230     is unchanged since the last compilation.</para>
231
232     <para>If we now modify the source of D (or pretend to: using Unix
233     command <literal>touch</literal> on the source file is handy for
234     this), the compiler will no longer be able to use the object file,
235     because it might be out of date:</para>
236
237 <screen>
238 Main> :! touch D.hs
239 Main> :reload
240 Compiling D                ( D.hs, interpreted )
241 Skipping  C                ( C.hs, interpreted )
242 Skipping  B                ( B.hs, interpreted )
243 Skipping  A                ( A.hs, interpreted )
244 Ok, modules loaded: A, B, C, D.
245 Main> 
246 </screen>
247
248     <para>Note that module D was compiled, but in this instance
249     because its source hadn't really changed, its interface remained
250     the same, and the recompilation checker determined that A, B and C
251     didn't need to be recompiled.</para>
252
253     <para>So let's try compiling one of the other modules:</para>
254
255 <screen>
256 Main> :! ghc -c C.hs
257 Main> :load A
258 Compiling D                ( D.hs, interpreted )
259 Compiling C                ( C.hs, interpreted )
260 Compiling B                ( B.hs, interpreted )
261 Compiling A                ( A.hs, interpreted )
262 Ok, modules loaded: A, B, C, D.
263 </screen>
264
265     <para>We didn't get the compiled version of C!  What happened?
266     Well, in GHCi a compiled module may only depend on other compiled
267     modules, and in this case C depends on D, which doesn't have an
268     object file, so GHCi also rejected C's object file.  Ok, so let's
269     also compile D:</para>
270
271 <screen>
272 Main> :! ghc -c D.hs
273 Main> :reload
274 Ok, modules loaded: A, B, C, D.
275 </screen>
276
277     <para>Nothing happened!  Here's another lesson: newly compiled
278     modules aren't picked up by <literal>:reload</literal>, only
279     <literal>:load</literal>:</para>
280
281 <screen>
282 Main> :load A
283 Skipping  D                ( D.hs, D.o )
284 Skipping  C                ( C.hs, C.o )
285 Compiling B                ( B.hs, interpreted )
286 Compiling A                ( A.hs, interpreted )
287 Ok, modules loaded: A, B, C, D.
288 </screen>
289
290     <para>HINT: since GHCi will only use a compiled object file if it
291     can sure that the compiled version is up-to-date, a good technique
292     when working on a large program is to occasionally run
293     <literal>ghc --make</literal> to compile the whole project (say
294     before you go for lunch :-), then continue working in the
295     interpreter.  As you modify code, the new modules will be
296     interpreted, but the rest of the project will remain
297     compiled.</para>
298
299   </sect1>
300
301   <sect1>
302     <title>Interactive evaluation at the prompt</title>
303
304     <para>When you type an expression at the prompt, GHCi immediately
305     evaluates and prints the result.  But that's not the whole story:
306     if you type something of type <literal>IO a</literal> for some
307     <literal>a</literal>, then GHCi <emphasis>executes</emphasis> it
308     as an IO-computation, and doesn't attempt to print the
309     result:.</para>
310
311 <screen>
312 Prelude> "hello"
313 "hello"
314 Prelude> putStrLn "hello"
315 hello
316 </screen>
317
318     <para>What actually happens is that GHCi typechecks the
319     expression, and if it doesn't have an <literal>IO</literal> type,
320     then it transforms it as follows: an expression
321     <replaceable>e</replaceable> turns into 
322 <screen>     
323              let it = <replaceable>e</replaceable>;
324              print it
325 </screen>
326     which is then run as an IO-action.</para>
327
328     <para>Hence, the original expression must have a type which is an
329     instance of the <literal>Show</literal> class, or GHCi will
330     complain:</para>
331
332 <screen>
333 Prelude> id
334 No instance for `Show (a -> a)'
335 arising from use of `print'
336 in a `do' expression pattern binding: print it
337 </screen>
338
339     <para>The error message contains some clues as to the
340     transformation happening internally.</para>
341
342     <sect2 id="ghci-scope">
343       <title>What's really in scope at the prompt?</title> 
344
345        <para>When you type an expression at the prompt, what
346        identifiers and types are in scope?  GHCi has a concept of a
347        <firstterm>context</firstterm> module, which can be set using
348        the <literal>:module</literal> command.</para>
349
350       <para>The context module is shown in the prompt: for example,
351       the prompt <literal>Prelude></literal> indicates that the
352       current context for evaluating expressions is the Haskell
353       <literal>Prelude</literal> module.  The Prelude is the default
354       context when you start up GHCi.</para>
355       <indexterm><primary><literal>Prelude</literal></primary></indexterm>
356
357       <para>Exactly which entities are in scope in a given context
358       depends on whether the context module is compiled or
359       interpreted:</para>
360
361       <itemizedlist>
362         <listitem>
363           <para>If the context module is interpreted, then everything
364           that was in scope during compilation of that module is also
365           in scope at the prompt, i.e. all the imports and any
366           top-level functions, types and classes defined in that
367           module.</para>
368         </listitem>
369
370         <listitem>
371           <para>If the context module comes from a package, or is
372           otherwise compiled, then only the exports of that module are
373           in scope at the prompt.  So for example, when the current
374           context module is <literal>Prelude</literal>, everything the
375           <literal>Prelude</literal> exports is in scope, but if we
376           switch context to eg. <literal>Time</literal>, then
377           everything from the <literal>Prelude</literal> is now
378           invisible.</para>
379         </listitem>
380       </itemizedlist>
381
382       <para>The reason for this unfortunate distinction is boring: for
383       a compiled module when the source isn't available, the compiler
384       has no way of knowing what was in scope when the module was
385       compiled (and we don't store this information in the interface
386       file).  However, in practice it shouldn't be a problem: if you
387       want both <literal>Time</literal> and <literal>Prelude</literal>
388       in scope at the same time, just create a file containing the
389       line <literal>import Time</literal> and load it into
390       GHCi.</para>
391
392       <para>To make life slightly easier, the GHCi prompt also behaves
393       as if there is an implicit <literal>import qualified</literal>
394       declaration for every module in every package, and every module
395       currently loaded into GHCi.  So in the above example where the
396       <literal>Prelude</literal> was invisible, we can always get at
397       <literal>Prelude</literal> identifiers by qualifying them, eg.
398       <literal>Prelude.map</literal>.</para>
399     </sect2>
400   
401     <sect2>
402       <title>Using <literal>do-</literal>notation at the prompt</title>
403       <indexterm><primary>do-notation</primary><secondary>in GHCi</secondary></indexterm>
404       <indexterm><primary>statements</primary><secondary>in GHCi</secondary></indexterm>
405       
406       <para>GHCi actually accepts <firstterm>statements</firstterm>
407       rather than just expressions at the prompt.  This means you can
408       bind values and functions to names, and use them in future
409       expressions or statements.</para>
410
411       <para>The syntax of a statement accepted at the GHCi prompt is
412       exactly the same as the syntax of a statement in a Haskell
413       <literal>do</literal> expression.  However, there's no monad
414       overloading here: statements typed at the prompt must be in the
415       <literal>IO</literal> monad.</para>
416
417       <para>Here's an example:</para>
418 <screen>
419 Prelude> x <- return 42
420 Prelude> print x
421 42
422 Prelude>
423 </screen>
424       <para>The statement <literal>x <- return 42</literal> means
425       &ldquo;execute <literal>return 42</literal> in the
426       <literal>IO</literal> monad, and bind the result to
427       <literal>x</literal>&rdquo;.  We can then use
428       <literal>x</literal> in future statements, for example to print
429       it as we did above.</para>
430
431       <para>Of course, you can also bind normal non-IO expressions
432       using the <literal>let</literal>-statement:</para>
433 <screen>
434 Prelude> let x = 42
435 Prelude> print x
436 42
437 Prelude>
438 </screen>
439       <para>An important difference between the two types of binding
440       is that the monadic bind (<literal>p <- e</literal>) is
441       <emphasis>strict</emphasis> (it evaluates <literal>e</literal>),
442       whereas with the <literal>let</literal> form, the expression
443       isn't evaluated immediately:</para>
444 <screen>
445 Prelude> let x = error "help!"
446 Prelude> print x
447 *** Exception: help!
448 Prelude>
449 </screen>
450       <para>Any exceptions raised during the evaluation or execution
451       of the statement are caught and printed by the GHCi command line
452       interface (see <xref linkend="sec-Exception"> for more
453       information on GHC's Exception support).</para>
454
455       <para>Every new binding shadows any existing bindings of the
456       same name, including entities that are in scope in the current
457       module context.</para>
458
459       <para>WARNING: temporary bindings introduced at the prompt only
460       last until the next <literal>:load</literal> or
461       <literal>:reload</literal> command, at which time they will be
462       simply lost.  However, they do survive a change of context with
463       <literal>:module</literal>: the temporary bindings just move to
464       the new location.</para>
465
466       <para>HINT: if you turn on the <literal>+t</literal> option,
467       GHCi will show the type of each variable bound by a statement.
468       For example:</para>
469       <indexterm><primary><literal>+t</literal></primary></indexterm>
470 <screen>
471 Prelude> :set +t
472 Prelude> let (x:xs) = [1..]
473 x :: Integer
474 xs :: [Integer]
475 </screen>
476
477     </sect2>
478
479     <sect2>
480       <title>The <literal>it</literal> variable</title>
481       <indexterm><primary><literal>it</literal></primary>
482       </indexterm>
483       
484       <para>Whenever an expression (or a non-binding statement, to be
485       precise) is typed at the prompt, GHCi implicitly binds its value
486       to the variable <literal>it</literal>.  For example:</para>
487 <screen>
488 Prelude> 1+2
489 3
490 Prelude> it * 2
491 6
492 </screen>
493
494       <para>This is a result of the translation mentioned earlier,
495       namely that an expression <replaceable>e</replaceable> is
496       translated to
497 <screen>     
498              let it = <replaceable>e</replaceable>;
499              print it
500 </screen>
501       before execution, resulting in a binding for
502       <literal>it</literal>.</para>
503
504       <para>If the expression was of type <literal>IO a</literal> for
505       some <literal>a</literal>, then <literal>it</literal> will be
506       bound to the result of the <literal>IO</literal> computation,
507       which is of type <literal>a</literal>.  eg.:</para>
508 <screen>
509 Prelude> Time.getClockTime
510 Prelude> print it
511 Wed Mar 14 12:23:13 GMT 2001
512 </screen>
513
514       <para>The corresponding translation for an IO-typed
515       <replaceable>e</replaceable> is
516 <screen>     
517              it <- <replaceable>e</replaceable>
518 </screen>
519       </para>
520
521       <para>Note that <literal>it</literal> is shadowed by the new
522       value each time you evaluate a new expression, and the old value
523       of <literal>it</literal> is lost.</para>
524
525     </sect2>
526   </sect1>
527
528   <sect1 id="ghci-invokation">
529     <title>Invoking GHCi</title>
530     <indexterm><primary>invoking</primary><secondary>GHCi</secondary></indexterm>
531     <indexterm><primary><option>--interactive</option></primary></indexterm>
532
533     <para>GHCi is invoked with the command <literal>ghci</literal> or
534     <literal>ghc --interactive</literal>.  One or more modules or
535     filenames can also be specified on the command line; this
536     instructs GHCi to load the specified modules or filenames (and all
537     the modules they depend on), just as if you had said
538     <literal>:load <replaceable>modules</replaceable></literal> at the
539     GHCi prompt (see <xref linkend="ghci-commands">).  For example, to
540     start GHCi and load the program whose topmost module is in the
541     file <literal>Main.hs</literal>, we could say:</para>
542
543 <screen>
544 $ ghci Main.hs
545 </screen>
546
547     <para>Most of the command-line options accepted by GHC (see <xref
548     linkend="using-ghc">) also make sense in interactive mode.  The ones
549     that don't make sense are mostly obvious; for example, GHCi
550     doesn't generate interface files, so options related to interface
551     file generation won't have any effect.</para>
552
553     <sect2>
554       <title>Packages</title>
555       <indexterm><primary>packages</primary><secondary>with GHCi</secondary></indexterm>
556
557       <para>GHCi can make use of all the packages that come with GHC,
558       For example, to start up GHCi with the <literal>text</literal>
559       package loaded:</para>
560
561 <screen>
562 $ ghci -package text
563    ___         ___ _
564   / _ \ /\  /\/ __(_)
565  / /_\// /_/ / /  | |      GHC Interactive, version 5.00, For Haskell 98.
566 / /_\\/ __  / /___| |      http://www.haskell.org/ghc/
567 \____/\/ /_/\____/|_|      Type :? for help.
568
569 Loading package std ... linking ... done.
570 Loading package lang ... linking ... done.
571 Loading package text ... linking ... done.
572 Prelude> 
573 </screen>      
574
575       <para>Note that GHCi also loaded the <literal>lang</literal>
576       package even though we didn't ask for it: that's because the
577       <literal>text</literal> package makes use of one or more of the
578       modules in <literal>lang</literal>, and therefore has a
579       dependency on it.</para>
580
581       <para>The following command works to load new packages into a
582       running GHCi:</para>
583
584 <screen>
585 Prelude> :set -package <replaceable>name</replaceable>
586 </screen>
587
588       <para>But note that doing this will cause all currently loaded
589       modules to be unloaded, and you'll be dumped back into the
590       Prelude.</para>
591     </sect2>
592
593     <sect2>
594       <title>Extra libraries</title>
595       <indexterm><primary>libraries</primary><secondary>with GHCi</secondary></indexterm>
596       
597       <para>Extra libraries may be specified on the command line using
598       the normal <literal>-l<replaceable>lib</replaceable></literal>
599       option.  For example, to load the &ldquo;m&rdquo; library:</para>
600
601 <screen>
602 $ ghci -lm
603 </screen>
604
605       <para>On systems with <literal>.so</literal>-style shared
606       libraries, the actual library loaded will the
607       <filename>lib<replaceable>lib</replaceable>.so</filename>.  GHCi
608       searches the following places for libraries, in this order:</para>
609
610       <itemizedlist>
611         <listitem>
612           <para>Paths specified using the
613           <literal>-L<replaceable>path</replaceable></literal>
614           command-line option,</para>
615         </listitem>
616         <listitem>
617           <para>the standard library search path for your system,
618           which on some systems may be overriden by setting the
619           <literal>LD_LIBRARY_PATH</literal> environment
620           variable.</para>
621         </listitem>
622       </itemizedlist>
623
624       <para>On systems with <literal>.dll</literal>-style shared
625       libraries, the actual library loaded will be
626       <filename><replaceable>lib</replaceable>.dll</filename>.  Again,
627       GHCi will signal an error if it can't find the library.</para>
628
629       <para>GHCi can also load plain object files
630       (<literal>.o</literal> or <literal>.obj</literal> depending on
631       your platform) from the command-line.  Just add the name the
632       object file to the command line.</para>
633     </sect2>
634
635   </sect1>
636
637   <sect1 id="ghci-commands">
638     <title>GHCi commands</title>
639
640     <para>GHCi commands all begin with
641     &lsquo;<literal>:</literal>&rsquo; and consist of a single command
642     name followed by zero or more parameters.  The command name may be
643     abbreviated, as long as the abbreviation is not ambiguous.  All of
644     the builtin commands, with the exception of
645     <literal>:unset</literal> and <literal>:undef</literal>, may be
646     abbreviated to a single letter.</para>
647
648     <variablelist>
649       <varlistentry>
650         <term><literal>:add</literal>
651         <replaceable>module</replaceable> ...</term>
652         <indexterm><primary><literal>:add</literal></primary></indexterm>
653         <listitem>
654           <para>Add <replaceable>module</replaceable>(s) to the
655           current <firstterm>target set</firstterm>, and perform a
656           reload.</para>
657         </listitem>
658       </varlistentry>
659
660       <varlistentry>
661         <term><literal>:cd</literal> <replaceable>dir</replaceable></term>
662         <indexterm><primary><literal>:cd</literal></primary></indexterm>
663         <listitem>
664           <para>Changes the current working directory to
665           <replaceable>dir</replaceable>.  A
666           &lsquo;<literal>&tilde;</literal>&rsquo; symbol at the
667           beginning of <replaceable>dir</replaceable> will be replaced
668           by the contents of the environment variable
669           <literal>HOME</literal>.</para>
670         </listitem>
671       </varlistentry>
672
673       <varlistentry>
674         <term><literal>:def</literal> <replaceable>name</replaceable> <replaceable>expr</replaceable></term>
675         <indexterm><primary><literal>:def</literal></primary></indexterm>
676         <listitem>
677           <para>The command <literal>:def</literal>
678           <replaceable>name</replaceable>
679           <replaceable>expr</replaceable> defines a new GHCi command
680           <literal>:<replaceable>name</replaceable></literal>,
681           implemented by the Haskell expression
682           <replaceable>expr</replaceable>, which must have type
683           <literal>String -> IO String</literal>.  When
684           <literal>:<replaceable>name</replaceable>
685           <replaceable>args</replaceable></literal> is typed at the
686           prompt, GHCi will run the expression
687           <literal>(<replaceable>name</replaceable>
688           <replaceable>args</replaceable>)</literal>, take the
689           resulting <literal>String</literal>, and feed it back into
690           GHCi as a new sequence of commands.  Separate commands in
691           the result must be separated by
692           &lsquo;<literal>\n</literal>&rsquo;.</para>
693
694           <para>That's all a little confusing, so here's a few
695           examples.  To start with, here's a new GHCi command which
696           doesn't take any arguments or produce any results, it just
697           outputs the current date & time:</para>
698
699 <screen>
700 Prelude> let date _ = Time.getClockTime >>= print >> return ""
701 Prelude> :def date date
702 Prelude> :date
703 Fri Mar 23 15:16:40 GMT 2001
704 </screen>
705
706           <para>Here's an example of a command that takes an argument.
707           It's a re-implementation of <literal>:cd</literal>:</para>
708
709 <screen>
710 Prelude> let mycd d = Directory.setCurrentDirectory d >> return ""
711 Prelude> :def mycd mycd
712 Prelude> :mycd ..
713 </screen>
714
715           <para>Or I could define a simple way to invoke
716           &ldquo;<literal>ghc --make Main</literal>&rdquo; in the
717           current directory:</para>
718
719 <screen>
720 Prelude> :def make (\_ -> return ":! ghc --make Main")
721 </screen>
722
723         </listitem>
724       </varlistentry>
725
726       <varlistentry>
727         <term><literal>:help</literal></term>
728         <indexterm><primary><literal>:help</literal></primary></indexterm>
729         <term><literal>:?</literal></term>
730         <indexterm><primary><literal>:?</literal></primary></indexterm>
731         <listitem>
732           <para>Displays a list of the available commands.</para>
733         </listitem>
734       </varlistentry>
735
736       <varlistentry>
737         <term><literal>:info</literal> <replaceable>name</replaceable>
738         ...</term>
739         <indexterm><primary><literal>:info</literal></primary>
740         </indexterm>
741         <listitem>
742           <para>Displays information about the given name(s).  For
743           example, if <replaceable>name</replaceable> is a class, then
744           the class methods and their types will be printed;  if
745           <replaceable>name</replaceable> is a type constructor, then
746           its definition will be printed;  if
747           <replaceable>name</replaceable> is a function, then its type
748           will be printed.  If <replaceable>name</replaceable> has
749           been loaded from a source file, then GHCi will also display
750           the location of its definition in the source.</para>
751         </listitem>
752       </varlistentry>
753
754       <varlistentry>
755         <term><literal>:load</literal>
756         <replaceable>module</replaceable> ...</term>
757         <indexterm><primary><literal>:load</literal></primary></indexterm>
758         <listitem>
759           <para>Recursively loads the specified
760           <replaceable>module</replaceable>s, and all the modules they
761           depend on.  Here, each <replaceable>module</replaceable>
762           must be a module name or filename, but may not be the name
763           of a module in a package.</para>
764
765           <para>All previously loaded modules, except package modules,
766           are forgotten.  The new set of modules is known as the
767           <firstterm>target set</firstterm>.</para>
768
769           <para>After a <literal>:load</literal> command, the current
770           context is set to:</para>
771
772           <itemizedlist>
773             <listitem>
774               <para><replaceable>module</replaceable>, if it was loaded
775               successfully, or</para>
776             </listitem>
777             <listitem>
778               <para>the most recently successfully loaded module, if
779               any other modules were loaded as a result of the current
780               <literal>:load</literal>, or</para>
781             </listitem>
782             <listitem>
783               <para><literal>Prelude</literal> otherwise.</para>
784             </listitem>
785           </itemizedlist>
786         </listitem>
787       </varlistentry>
788
789       <varlistentry>
790         <term><literal>:module</literal> <replaceable>module</replaceable></term>
791         <indexterm><primary><literal>:module</literal></primary></indexterm>
792         <listitem>
793           <para>Sets the current context for statements typed at the
794           prompt to <replaceable>module</replaceable>, which must be a
795           module name which is already loaded or in a package.  See
796           <xref linkend="ghci-scope"> for more information on what
797           effect the context has on what entities are in scope at the
798           prompt.</para>
799         </listitem>
800       </varlistentry>
801
802       <varlistentry>
803         <term><literal>:quit</literal></term>
804         <indexterm><primary><literal>:quit</literal></primary></indexterm>
805         <listitem>
806           <para>Quits GHCi.  You can also quit by typing a control-D
807           at the prompt.</para>
808         </listitem>
809       </varlistentry>
810
811       <varlistentry>
812         <term><literal>:reload</literal></term>
813         <indexterm><primary><literal>:reload</literal></primary></indexterm>
814         <listitem>
815           <para>Attempts to reload the current target set (see
816           <literal>:load</literal>) if any of the modules in the set,
817           or any dependent module, has changed.  Note that this may
818           entail loading new modules, or dropping modules which are no
819           longer indirectly required by the target.</para>
820         </listitem>
821       </varlistentry>
822
823       <varlistentry>
824         <term><literal>:set</literal> <optional><replaceable>option</replaceable>...</optional></term>
825         <indexterm><primary><literal>:set</literal></primary></indexterm>
826         <listitem>
827           <para>Sets various options.  See <xref linkend="ghci-set">
828           for a list of available options.  The
829           <literal>:set</literal> command by itself shows which
830           options are currently set.</para>
831         </listitem>
832       </varlistentry>
833
834       <varlistentry>
835         <term><literal>:type</literal> <replaceable>expression</replaceable></term>
836         <indexterm><primary><literal>:type</literal></primary></indexterm>
837         <listitem>
838           <para>Infers and prints the type of
839           <replaceable>expression</replaceable>, including explicit
840           forall quantifiers for polymorphic types.  The monomorphism
841           restriction is <emphasis>not</emphasis> applied to the
842           expression during type inference.</para>
843         </listitem>
844       </varlistentry>
845
846       <varlistentry>
847         <term><literal>:undef</literal> <replaceable>name</replaceable></term>
848         <indexterm><primary><literal>:undef</literal></primary></indexterm>
849         <listitem>
850           <para>Undefines the user-defined command
851           <replaceable>name</replaceable> (see <literal>:def</literal>
852           above).</para>
853         </listitem>
854       </varlistentry>
855
856       <varlistentry>
857         <term><literal>:unset</literal> <replaceable>option</replaceable>...</term>
858         <indexterm><primary><literal>:unset</literal></primary></indexterm>
859         <listitem>
860           <para>Unsets certain options.  See <xref linkend="ghci-set">
861           for a list of available options.</para>
862         </listitem>
863       </varlistentry>
864
865       <varlistentry>
866         <term><literal>:!</literal> <replaceable>command</replaceable>...</term>
867         <indexterm><primary><literal>:!</literal></primary></indexterm>
868         <indexterm><primary>shell commands</primary><secondary>in GHCi</secondary></indexterm>
869         <listitem>
870           <para>Executes the shell command
871           <replaceable>command</replaceable>.</para>
872         </listitem>
873       </varlistentry>
874
875     </variablelist>
876   </sect1>
877
878   <sect1 id="ghci-set">
879     <title>The <literal>:set</literal> command</title>
880     <indexterm><primary><literal>:set</literal></primary></indexterm>
881
882     <para>The <literal>:set</literal> command sets two types of
883     options: GHCi options, which begin with
884     &lsquo;<literal>+</literal>&rdquo; and &ldquo;command-line&rdquo;
885     options, which begin with &lsquo;-&rsquo;.  </para>
886
887     <sect2>
888       <title>GHCi options</title>
889       <indexterm><primary>options</primary><secondary>GHCi</secondary>
890       </indexterm>
891
892       <para>GHCi options may be set using <literal>:set</literal> and
893       unset using <literal>:unset</literal>.</para>
894
895       <para>The available GHCi options are:</para>
896
897       <variablelist>
898         <varlistentry>
899           <term><literal>+r</literal></term>
900           <indexterm><primary><literal>+r</literal></primary></indexterm>
901           <indexterm><primary>CAFs</primary><secondary>in GHCi</secondary></indexterm>
902           <indexterm><primary>Constant Applicative Form</primary><see>CAFs</see></indexterm>
903           <listitem>
904             <para>Normally, any evaluation of top-level expressions
905             (otherwise known as CAFs or Constant Applicative Forms) in
906             loaded modules is retained between evaluations.  Turning
907             on <literal>+r</literal> causes all evaluation of
908             top-level expressions to be discarded after each
909             evaluation (they are still retained
910             <emphasis>during</emphasis> a single evaluation).</para>
911           
912             <para>This option may help if the evaluated top-level
913             expressions are consuming large amounts of space, or if
914             you need repeatable performance measurements.</para>
915           </listitem>
916         </varlistentry>
917
918         <varlistentry>
919           <term><literal>+s</literal></term>
920           <indexterm><primary><literal>+s</literal></primary></indexterm>
921           <listitem>
922             <para>Display some stats after evaluating each expression,
923             including the elapsed time and number of bytes allocated.
924             NOTE: the allocation figure is only accurate to the size
925             of the storage manager's allocation area, because it is
926             calculated at every GC.  Hence, you might see values of
927             zero if no GC has occurred.</para>
928           </listitem>
929         </varlistentry>
930
931         <varlistentry>
932           <term><literal>+t</literal></term>
933           <indexterm><primary><literal>+t</literal></primary></indexterm>
934           <listitem>
935             <para>Display the type of each variable bound after a
936             statement is entered at the prompt.  If the statement is a
937             single expression, then the only variable binding will be
938             for the variable
939             &lsquo;<literal>it</literal>&rsquo;.</para>
940           </listitem>
941         </varlistentry>
942       </variablelist>
943     </sect2>
944
945     <sect2>
946       <title>Setting GHC command-line options in GHCi</title>
947
948       <para>Normal GHC command-line options may also be set using
949       <literal>:set</literal>.  For example, to turn on
950       <option>-fglasgow-exts</option>, you would say:</para>
951
952 <screen>
953 Prelude> :set -fglasgow-exts
954 </screen>
955       
956       <para>Any GHC command-line option that is designated as
957       <firstterm>dynamic</firstterm> (see the table in <xref
958       linkend="flag-reference">), may be set using
959       <literal>:set</literal>.  To unset an option, you can set the
960       reverse option:</para>
961       <indexterm><primary>dynamic</primary><secondary>options</secondary></indexterm>
962
963 <screen>
964 Prelude> :set -fno-glasgow-exts
965 </screen>
966
967       <para><xref linkend="flag-reference"> lists the reverse for each
968       option where applicable.</para>
969
970       <para>Certain static options (<option>-package</option>,
971       <option>-I</option>, <option>-i</option>, and
972       <option>-l</option> in particular) will also work, but some may
973       not take effect until the next reload.</para>
974       <indexterm><primary>static</primary><secondary>options</secondary></indexterm>
975     </sect2>
976   </sect1>
977
978   <sect1 id="ghci-dot-files">
979     <title>The <filename>.ghci</filename> file</title>
980     <indexterm><primary><filename>.ghci</filename></primary><secondary>file</secondary>
981     </indexterm>
982     <indexterm><primary>startup</primary><secondary>files, GHCi</secondary>
983     </indexterm>
984
985     <para>When it starts, GHCi always reads and executes commands from
986     <filename>$HOME/.ghci</filename>, followed by
987     <filename>./.ghci</filename>.</para>
988
989     <para>The <filename>.ghci</filename> in your home directory is
990     most useful for turning on favourite options (eg. <literal>:set
991     +s</literal>), and defining useful macros.  Placing a
992     <filename>.ghci</filename> file in a directory with a Haskell
993     project is a useful way to set certain project-wide options so you
994     don't have to type them everytime you start GHCi: eg. if your
995     project uses GHC extensions and CPP, and has source files in three
996     subdirectories A B and C, you might put the following lines in
997     <filename>.ghci</filename>:</para>
998
999 <screen>
1000 :set -fglasgow-exts -cpp
1001 :set -iA:B:C
1002 </screen>
1003
1004     <para>(Note that strictly speaking the <option>-i</option> flag is
1005     a static one, but in fact it works to set it using
1006     <literal>:set</literal> like this.  The changes won't take effect
1007     until the next <literal>:load</literal>, though.)</para>
1008
1009     <para>Two command-line options control whether the
1010     <filename>.ghci</filename> files are read:</para>
1011
1012     <variablelist>
1013       <varlistentry>
1014         <term><option>-ignore-dot-ghci</option></term>
1015         <indexterm><primary><option>-ignore-dot-ghci</option></primary>
1016         </indexterm>
1017         <listitem>
1018           <para>Don't read either <filename>./.ghci</filename> or
1019           <filename>$HOME/.ghci</filename> when starting up.</para>
1020         </listitem>
1021       </varlistentry>
1022       <varlistentry>
1023         <term><option>-read-dot-ghci</option></term>
1024         <indexterm><primary><option>-read-dot-ghci</option></primary>
1025         </indexterm>
1026         <listitem>
1027           <para>Read <filename>.ghci</filename> and
1028           <filename>$HOME/.ghci</filename>.  This is normally the
1029           default, but the <option>-read-dot-ghci</option> option may
1030           be used to override a previous
1031           <option>-ignore-dot-ghci</option> option.</para>
1032         </listitem>
1033       </varlistentry>
1034     </variablelist>
1035
1036   </sect1>
1037
1038   <sect1>
1039     <title>FAQ and Things To Watch Out For</title>
1040     
1041     <variablelist>
1042       <varlistentry>
1043         <term>GHCi complains about <function>main</function> not being
1044         in scope when I load a module.</term>
1045         <indexterm><primary><function>main</function></primary><secondary>with GHCi</secondary>
1046         </indexterm>
1047         <listitem>
1048           <para>You probably omitted the <literal>module</literal>
1049           declaration at the top of the module, which causes the
1050           module name to default to <literal>Main</literal>.  In
1051           Haskell, the <literal>Main</literal> module must define a
1052           function called <function>main</function>.  Admittedly this
1053           doesn't make a great deal of sense for an interpreter, but
1054           the rule was kept for compatibility with GHC.</para>
1055         </listitem>
1056       </varlistentry>
1057
1058       <varlistentry>
1059         <term><literal>System.getArgs</literal> returns GHCi's command
1060         line arguments!</term>
1061         <listitem>
1062           <para>Yes, it does.</para>
1063         </listitem>
1064       </varlistentry>
1065
1066       <varlistentry>
1067         <term>The interpreter can't load modules with foreign export
1068         declarations!</term>
1069         <listitem>
1070           <para>Unfortunately not.  We haven't implemented it yet.
1071           Please compile any offending modules by hand before loading
1072           them into GHCi.</para>
1073         </listitem>
1074       </varlistentry>
1075
1076       <varlistentry>
1077         <term><literal>-O</literal> doesn't work with GHCi!</term>
1078         <indexterm><primary><option>-O</option></primary>
1079         </indexterm>
1080         <listitem>
1081           <para>For technical reasons, the bytecode compiler doesn't
1082           interact well with one of the optimisation passes, so we
1083           have disabled optimisation when using the interpreter.  This
1084           isn't a great loss: you'll get a much bigger win by
1085           compiling the bits of your code that need to go fast, rather
1086           than interpreting them with optimisation turned on.</para>
1087         </listitem>
1088       </varlistentry>
1089
1090       <varlistentry>
1091         <term>Unboxed tuples don't work with GHCi</term>
1092         <listitem>
1093           <para>That's right.  You can always compile a module that
1094           uses unboxed tuples and load it into GHCi, however.
1095           (Incidentally the previous point, namely that
1096           <literal>-O</literal> is incompatible with GHCi, is because
1097           the bytecode compiler can't deal with unboxed
1098           tuples).</para>
1099         </listitem>
1100       </varlistentry>
1101
1102       <varlistentry>
1103         <term>Concurrent threads don't carry on running when GHCi is
1104         waiting for input.</term>
1105         <listitem>
1106           <para>No, they don't.  This is because the Haskell binding
1107           to the GNU readline library doesn't support reading from the
1108           terminal in a non-blocking way, which is required to work
1109           properly with GHC's concurrency model.</para>
1110         </listitem>
1111       </varlistentry>
1112
1113       <varlistentry>
1114         <term>After using <literal>getContents</literal>, I can't use
1115         <literal>stdin</literal> again until I do
1116         <literal>:load</literal> or <literal>:reload</literal>.</term>
1117
1118         <listitem>
1119           <para>This is the defined behaviour of
1120           <literal>getContents</literal>: it puts the stdin Handle in
1121           a state known as <firstterm>semi-closed</firstterm>, wherein
1122           any further I/O operations on it are forbidden.  Because I/O
1123           state is retained between computations, the semi-closed
1124           state persists until the next <literal>:load</literal> or
1125           <literal>:reload</literal> command.</para>
1126
1127           <para>You can make <literal>stdin</literal> reset itself
1128           after every evaluation by giving GHCi the command
1129           <literal>:set +r</literal>.  This works because
1130           <literal>stdin</literal> is just a top-level expression that
1131           can be reverted to its unevaluated state in the same way as
1132           any other top-level expression (CAF).</para>
1133         </listitem>
1134       </varlistentry>
1135
1136     </variablelist>
1137   </sect1>
1138
1139 </chapter>
1140
1141 <!-- Emacs stuff:
1142      ;;; Local Variables: ***
1143      ;;; mode: sgml ***
1144      ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***
1145      ;;; End: ***
1146  -->