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