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