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