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