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