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