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