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