1 <?xml version="1.0" encoding="iso-8859-1"?>
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>
9 <para>The ‘i’ stands for “Interactive”</para>
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>
23 <sect1 id="ghci-introduction">
24 <title>Introduction to GHCi</title>
26 <para>Let's start with an example GHCi session. You can fire up
27 GHCi with the command <literal>ghci</literal>:</para>
31 GHCi, version 6.8.1: http://www.haskell.org/ghc/ :? for help
32 Loading package base ... linking ... done.
36 <para>There may be a short pause while GHCi loads the prelude and
37 standard libraries, after which the prompt is shown. As the banner
38 says, you can type <literal>:?</literal> to see the list of commands
39 available, and a half line description of each of them.</para>
41 <para>We'll explain most of these commands as we go along. For
42 Hugs users: many things work the same as in Hugs, so you should be
43 able to get going straight away.</para>
45 <para>Haskell expressions can be typed at the prompt:</para>
46 <indexterm><primary>prompt</primary><secondary>GHCi</secondary>
52 Prelude> let x = 42 in x / 9
57 <para>GHCi interprets the whole line as an expression to evaluate.
58 The expression may not span several lines - as soon as you press
59 enter, GHCi will attempt to evaluate it.</para>
62 <sect1 id="loading-source-files">
63 <title>Loading source files</title>
65 <para>Suppose we have the following Haskell source code, which we
66 place in a file <filename>Main.hs</filename>:</para>
75 <para>You can save <filename>Main.hs</filename> anywhere you like,
76 but if you save it somewhere other than the current
77 directory<footnote><para>If you started up GHCi from the command
78 line then GHCi's current directory is the same as the current
79 directory of the shell from which it was started. If you started
80 GHCi from the “Start” menu in Windows, then the
81 current directory is probably something like
82 <filename>C:\Documents and Settings\<replaceable>user
83 name</replaceable></filename>.</para> </footnote> then we will
84 need to change to the right directory in GHCi:</para>
87 Prelude> :cd <replaceable>dir</replaceable>
90 <para>where <replaceable>dir</replaceable> is the directory (or
91 folder) in which you saved <filename>Main.hs</filename>.</para>
93 <para>To load a Haskell source file into GHCi, use the
94 <literal>:load</literal> command:</para>
95 <indexterm><primary><literal>:load</literal></primary></indexterm>
99 Compiling Main ( Main.hs, interpreted )
100 Ok, modules loaded: Main.
104 <para>GHCi has loaded the <literal>Main</literal> module, and the
105 prompt has changed to “<literal>*Main></literal>” to
106 indicate that the current context for expressions typed at the
107 prompt is the <literal>Main</literal> module we just loaded (we'll
108 explain what the <literal>*</literal> means later in <xref
109 linkend="ghci-scope"/>). So we can now type expressions involving
110 the functions from <filename>Main.hs</filename>:</para>
117 <para>Loading a multi-module program is just as straightforward;
118 just give the name of the “topmost” module to the
119 <literal>:load</literal> command (hint: <literal>:load</literal>
120 can be abbreviated to <literal>:l</literal>). The topmost module
121 will normally be <literal>Main</literal>, but it doesn't have to
122 be. GHCi will discover which modules are required, directly or
123 indirectly, by the topmost module, and load them all in dependency
126 <sect2 id="ghci-modules-filenames">
127 <title>Modules vs. filenames</title>
128 <indexterm><primary>modules</primary><secondary>and filenames</secondary></indexterm>
129 <indexterm><primary>filenames</primary><secondary>of modules</secondary></indexterm>
131 <para>Question: How does GHC find the filename which contains
132 module <replaceable>M</replaceable>? Answer: it looks for the
133 file <literal><replaceable>M</replaceable>.hs</literal>, or
134 <literal><replaceable>M</replaceable>.lhs</literal>. This means
135 that for most modules, the module name must match the filename.
136 If it doesn't, GHCi won't be able to find it.</para>
138 <para>There is one exception to this general rule: when you load
139 a program with <literal>:load</literal>, or specify it when you
140 invoke <literal>ghci</literal>, you can give a filename rather
141 than a module name. This filename is loaded if it exists, and
142 it may contain any module you like. This is particularly
143 convenient if you have several <literal>Main</literal> modules
144 in the same directory and you can't call them all
145 <filename>Main.hs</filename>.</para>
147 <para>The search path for finding source files is specified with
148 the <option>-i</option> option on the GHCi command line, like
150 <screen>ghci -i<replaceable>dir<subscript>1</subscript></replaceable>:...:<replaceable>dir<subscript>n</subscript></replaceable></screen>
152 <para>or it can be set using the <literal>:set</literal> command
153 from within GHCi (see <xref
154 linkend="ghci-cmd-line-options"/>)<footnote><para>Note that in
155 GHCi, and <option>––make</option> mode, the <option>-i</option>
156 option is used to specify the search path for
157 <emphasis>source</emphasis> files, whereas in standard
158 batch-compilation mode the <option>-i</option> option is used to
159 specify the search path for interface files, see <xref
160 linkend="search-path"/>.</para> </footnote></para>
162 <para>One consequence of the way that GHCi follows dependencies
163 to find modules to load is that every module must have a source
164 file. The only exception to the rule is modules that come from
165 a package, including the <literal>Prelude</literal> and standard
166 libraries such as <literal>IO</literal> and
167 <literal>Complex</literal>. If you attempt to load a module for
168 which GHCi can't find a source file, even if there are object
169 and interface files for the module, you'll get an error
174 <title>Making changes and recompilation</title>
175 <indexterm><primary><literal>:reload</literal></primary></indexterm>
177 <para>If you make some changes to the source code and want GHCi
178 to recompile the program, give the <literal>:reload</literal>
179 command. The program will be recompiled as necessary, with GHCi
180 doing its best to avoid actually recompiling modules if their
181 external dependencies haven't changed. This is the same
182 mechanism we use to avoid re-compiling modules in the batch
183 compilation setting (see <xref linkend="recomp"/>).</para>
187 <sect1 id="ghci-compiled">
188 <title>Loading compiled code</title>
189 <indexterm><primary>compiled code</primary><secondary>in GHCi</secondary></indexterm>
191 <para>When you load a Haskell source module into GHCi, it is
192 normally converted to byte-code and run using the interpreter.
193 However, interpreted code can also run alongside compiled code in
194 GHCi; indeed, normally when GHCi starts, it loads up a compiled
195 copy of the <literal>base</literal> package, which contains the
196 <literal>Prelude</literal>.</para>
198 <para>Why should we want to run compiled code? Well, compiled
199 code is roughly 10x faster than interpreted code, but takes about
200 2x longer to produce (perhaps longer if optimisation is on). So
201 it pays to compile the parts of a program that aren't changing
202 very often, and use the interpreter for the code being actively
205 <para>When loading up source modules with <literal>:load</literal>,
206 GHCi normally looks for any corresponding compiled object files,
207 and will use one in preference to interpreting the source if
208 possible. For example, suppose we have a 4-module program
209 consisting of modules A, B, C, and D. Modules B and C both import
210 D only, and A imports both B & C:</para>
218 <para>We can compile D, then load the whole program, like this:</para>
220 Prelude> :! ghc -c D.hs
222 Compiling B ( B.hs, interpreted )
223 Compiling C ( C.hs, interpreted )
224 Compiling A ( A.hs, interpreted )
225 Ok, modules loaded: A, B, C, D.
229 <para>In the messages from the compiler, we see that there is no line
230 for <literal>D</literal>. This is because
231 it isn't necessary to compile <literal>D</literal>,
232 because the source and everything it depends on
233 is unchanged since the last compilation.</para>
235 <para>At any time you can use the command
236 <literal>:show modules</literal>
237 to get a list of the modules currently loaded
243 C ( C.hs, interpreted )
244 B ( B.hs, interpreted )
245 A ( A.hs, interpreted )
248 <para>If we now modify the source of D (or pretend to: using the Unix
249 command <literal>touch</literal> on the source file is handy for
250 this), the compiler will no longer be able to use the object file,
251 because it might be out of date:</para>
256 Compiling D ( D.hs, interpreted )
257 Ok, modules loaded: A, B, C, D.
261 <para>Note that module D was compiled, but in this instance
262 because its source hadn't really changed, its interface remained
263 the same, and the recompilation checker determined that A, B and C
264 didn't need to be recompiled.</para>
266 <para>So let's try compiling one of the other modules:</para>
269 *Main> :! ghc -c C.hs
271 Compiling D ( D.hs, interpreted )
272 Compiling B ( B.hs, interpreted )
273 Compiling C ( C.hs, interpreted )
274 Compiling A ( A.hs, interpreted )
275 Ok, modules loaded: A, B, C, D.
278 <para>We didn't get the compiled version of C! What happened?
279 Well, in GHCi a compiled module may only depend on other compiled
280 modules, and in this case C depends on D, which doesn't have an
281 object file, so GHCi also rejected C's object file. Ok, so let's
282 also compile D:</para>
285 *Main> :! ghc -c D.hs
287 Ok, modules loaded: A, B, C, D.
290 <para>Nothing happened! Here's another lesson: newly compiled
291 modules aren't picked up by <literal>:reload</literal>, only
292 <literal>:load</literal>:</para>
296 Compiling B ( B.hs, interpreted )
297 Compiling A ( A.hs, interpreted )
298 Ok, modules loaded: A, B, C, D.
301 <para>The automatic loading of object files can sometimes lead to
302 confusion, because non-exported top-level definitions of a module
303 are only available for use in expressions at the prompt when the
304 module is interpreted (see <xref linkend="ghci-scope" />). For
305 this reason, if you ask GHCi to load a filename rather than a
306 module name (e.g. <literal>:load Main.hs</literal> rather than
307 <literal>:load Main</literal>) then any existing object file will
308 be ignored and the module will be interpreted rather than
309 compiled. Using <literal>-fobject-code</literal> disables this
310 behaviour (see <xref linkend="ghci-obj" />).</para>
312 <para>HINT: since GHCi will only use a compiled object file if it
313 can be sure that the compiled version is up-to-date, a good technique
314 when working on a large program is to occasionally run
315 <literal>ghc ––make</literal> to compile the whole project (say
316 before you go for lunch :-), then continue working in the
317 interpreter. As you modify code, the changed modules will be
318 interpreted, but the rest of the project will remain
322 <sect1 id="interactive-evaluation">
323 <title>Interactive evaluation at the prompt</title>
325 <para>When you type an expression at the prompt, GHCi immediately
326 evaluates and prints the result:
328 Prelude> reverse "hello"
335 <sect2><title>I/O actions at the prompt</title>
337 <para>GHCi does more than simple expression evaluation at the prompt.
338 If you type something of type <literal>IO a</literal> for some
339 <literal>a</literal>, then GHCi <emphasis>executes</emphasis> it
340 as an IO-computation.
344 Prelude> putStrLn "hello"
347 Furthermore, GHCi will print the result of the I/O action if (and only
350 <listitem><para>The result type is an instance of <literal>Show</literal>.</para></listitem>
351 <listitem><para>The result type is not
352 <literal>()</literal>.</para></listitem>
354 For example, remembering that <literal>putStrLn :: String -> IO ()</literal>:
356 Prelude> putStrLn "hello"
358 Prelude> do { putStrLn "hello"; return "yes" }
364 <sect2 id="ghci-stmts">
365 <title>Using <literal>do-</literal>notation at the prompt</title>
366 <indexterm><primary>do-notation</primary><secondary>in GHCi</secondary></indexterm>
367 <indexterm><primary>statements</primary><secondary>in GHCi</secondary></indexterm>
369 <para>GHCi actually accepts <firstterm>statements</firstterm>
370 rather than just expressions at the prompt. This means you can
371 bind values and functions to names, and use them in future
372 expressions or statements.</para>
374 <para>The syntax of a statement accepted at the GHCi prompt is
375 exactly the same as the syntax of a statement in a Haskell
376 <literal>do</literal> expression. However, there's no monad
377 overloading here: statements typed at the prompt must be in the
378 <literal>IO</literal> monad.
380 Prelude> x <- return 42
385 The statement <literal>x <- return 42</literal> means
386 “execute <literal>return 42</literal> in the
387 <literal>IO</literal> monad, and bind the result to
388 <literal>x</literal>”. We can then use
389 <literal>x</literal> in future statements, for example to print
390 it as we did above.</para>
392 <para>If <option>-fprint-bind-result</option> is set then
393 GHCi will print the result of a statement if and only if:
396 <para>The statement is not a binding, or it is a monadic binding
397 (<literal>p <- e</literal>) that binds exactly one
401 <para>The variable's type is not polymorphic, is not
402 <literal>()</literal>, and is an instance of
403 <literal>Show</literal></para>
406 <indexterm><primary><option>-fprint-bind-result</option></primary></indexterm><indexterm><primary><option>-fno-print-bind-result</option></primary></indexterm>.
409 <para>Of course, you can also bind normal non-IO expressions
410 using the <literal>let</literal>-statement:</para>
417 <para>Another important difference between the two types of binding
418 is that the monadic bind (<literal>p <- e</literal>) is
419 <emphasis>strict</emphasis> (it evaluates <literal>e</literal>),
420 whereas with the <literal>let</literal> form, the expression
421 isn't evaluated immediately:</para>
423 Prelude> let x = error "help!"
429 <para>Note that <literal>let</literal> bindings do not automatically
430 print the value bound, unlike monadic bindings.</para>
432 <para>Hint: you can also use <literal>let</literal>-statements
433 to define functions at the prompt:</para>
435 Prelude> let add a b = a + b
440 <para>However, this quickly gets tedious when defining functions
441 with multiple clauses, or groups of mutually recursive functions,
442 because the complete definition has to be given on a single line,
443 using explicit braces and semicolons instead of layout:</para>
445 Prelude> let { f op n [] = n ; f op n (h:t) = h `op` f op n t }
446 Prelude> f (+) 0 [1..3]
450 <para>To alleviate this issue, GHCi commands can be split over
451 multiple lines, by wrapping them in <literal>:{</literal> and
452 <literal>:}</literal> (each on a single line of its own):</para>
455 Prelude| let { g op n [] = n
456 Prelude| ; g op n (h:t) = h `op` g op n t
459 Prelude> g (*) 1 [1..3]
462 <para>Such multiline commands can be used with any GHCi command,
463 and the lines between <literal>:{</literal> and
464 <literal>:}</literal> are simply merged into a single line for
465 interpretation. That implies that each such group must form a single
466 valid command when merged, and that no layout rule is used.
467 The main purpose of multiline commands is not to replace module
468 loading but to make definitions in .ghci-files (see <xref
469 linkend="ghci-dot-files"/>) more readable and maintainable.</para>
471 <para>Any exceptions raised during the evaluation or execution
472 of the statement are caught and printed by the GHCi command line
473 interface (for more information on exceptions, see the module
474 <literal>Control.Exception</literal> in the libraries
475 documentation).</para>
477 <para>Every new binding shadows any existing bindings of the
478 same name, including entities that are in scope in the current
479 module context.</para>
481 <para>WARNING: temporary bindings introduced at the prompt only
482 last until the next <literal>:load</literal> or
483 <literal>:reload</literal> command, at which time they will be
484 simply lost. However, they do survive a change of context with
485 <literal>:module</literal>: the temporary bindings just move to
486 the new location.</para>
488 <para>HINT: To get a list of the bindings currently in scope, use the
489 <literal>:show bindings</literal> command:</para>
492 Prelude> :show bindings
496 <para>HINT: if you turn on the <literal>+t</literal> option,
497 GHCi will show the type of each variable bound by a statement.
499 <indexterm><primary><literal>+t</literal></primary></indexterm>
502 Prelude> let (x:xs) = [1..]
509 <sect2 id="ghci-scope">
510 <title>What's really in scope at the prompt?</title>
512 <para>When you type an expression at the prompt, what
513 identifiers and types are in scope? GHCi provides a flexible
514 way to control exactly how the context for an expression is
515 constructed. Let's start with the simple cases; when you start
516 GHCi the prompt looks like this:</para>
518 <screen>Prelude></screen>
520 <para>Which indicates that everything from the module
521 <literal>Prelude</literal> is currently in scope. If we now
522 load a file into GHCi, the prompt will change:</para>
525 Prelude> :load Main.hs
526 Compiling Main ( Main.hs, interpreted )
530 <para>The new prompt is <literal>*Main</literal>, which
531 indicates that we are typing expressions in the context of the
532 top-level of the <literal>Main</literal> module. Everything
533 that is in scope at the top-level in the module
534 <literal>Main</literal> we just loaded is also in scope at the
535 prompt (probably including <literal>Prelude</literal>, as long
536 as <literal>Main</literal> doesn't explicitly hide it).</para>
539 <literal>*<replaceable>module</replaceable></literal> indicates
540 that it is the full top-level scope of
541 <replaceable>module</replaceable> that is contributing to the
542 scope for expressions typed at the prompt. Without the
543 <literal>*</literal>, just the exports of the module are
546 <para>We're not limited to a single module: GHCi can combine
547 scopes from multiple modules, in any mixture of
548 <literal>*</literal> and non-<literal>*</literal> forms. GHCi
549 combines the scopes from all of these modules to form the scope
550 that is in effect at the prompt.</para>
552 <para>NOTE: for technical reasons, GHCi can only support the
553 <literal>*</literal>-form for modules that are interpreted.
554 Compiled modules and package modules can only contribute their
555 exports to the current scope. This is why GHCi will always
556 interpret, not compile, a module if you specify its filename
557 rather than its module name to <literal>:load</literal>.</para>
559 <para>The scope is manipulated using the
560 <literal>:module</literal> command. For example, if the current
561 scope is <literal>Prelude</literal>, then we can bring into
562 scope the exports from the module <literal>IO</literal> like
567 Prelude IO> hPutStrLn stdout "hello\n"
572 <para>(Note: you can use <literal>import M</literal> as an
573 alternative to <literal>:module +M</literal>, and
574 <literal>:module</literal> can also be shortened to
575 <literal>:m</literal>). The full syntax of the
576 <literal>:module</literal> command is:</para>
579 :module <optional>+|-</optional> <optional>*</optional><replaceable>mod<subscript>1</subscript></replaceable> ... <optional>*</optional><replaceable>mod<subscript>n</subscript></replaceable>
582 <para>Using the <literal>+</literal> form of the
583 <literal>module</literal> commands adds modules to the current
584 scope, and <literal>-</literal> removes them. Without either
585 <literal>+</literal> or <literal>-</literal>, the current scope
586 is replaced by the set of modules specified. Note that if you
587 use this form and leave out <literal>Prelude</literal>, GHCi
588 will assume that you really wanted the
589 <literal>Prelude</literal> and add it in for you (if you don't
590 want the <literal>Prelude</literal>, then ask to remove it with
591 <literal>:m -Prelude</literal>).</para>
593 <para>The scope is automatically set after a
594 <literal>:load</literal> command, to the most recently loaded
595 "target" module, in a <literal>*</literal>-form if possible.
596 For example, if you say <literal>:load foo.hs bar.hs</literal>
597 and <filename>bar.hs</filename> contains module
598 <literal>Bar</literal>, then the scope will be set to
599 <literal>*Bar</literal> if <literal>Bar</literal> is
600 interpreted, or if <literal>Bar</literal> is compiled it will be
601 set to <literal>Prelude Bar</literal> (GHCi automatically adds
602 <literal>Prelude</literal> if it isn't present and there aren't
603 any <literal>*</literal>-form modules).</para>
605 <para>With multiple modules in scope, especially multiple
606 <literal>*</literal>-form modules, it is likely that name
607 clashes will occur. Haskell specifies that name clashes are
608 only reported when an ambiguous identifier is used, and GHCi
609 behaves in the same way for expressions typed at the
613 Hint: GHCi will tab-complete names that are in scope; for
614 example, if you run GHCi and type <literal>J<tab></literal>
615 then GHCi will expand it to “<literal>Just </literal>”.
619 <title><literal>:module</literal> and
620 <literal>:load</literal></title>
622 <para>It might seem that <literal>:module</literal> and
623 <literal>:load</literal> do similar things: you can use both
624 to bring a module into scope. However, there is a clear
625 difference. GHCi is concerned with two sets of modules:</para>
629 <para>The set of modules that are
630 currently <emphasis>loaded</emphasis>. This set is
632 by <literal>:load</literal>, <literal>:add</literal>
633 and <literal>:reload</literal>.
637 <para>The set of modules that are currently <emphasis>in
638 scope</emphasis> at the prompt. This set is modified
639 by <literal>:module</literal>, and it is also set
641 after <literal>:load</literal>, <literal>:add</literal>,
642 and <literal>:reload</literal>.</para>
646 <para>You cannot add a module to the scope if it is not
647 loaded. This is why trying to
648 use <literal>:module</literal> to load a new module results
649 in the message “<literal>module M is not
650 loaded</literal>”.</para>
653 <sect3 id="ghci-import-qualified">
654 <title>Qualified names</title>
656 <para>To make life slightly easier, the GHCi prompt also
657 behaves as if there is an implicit <literal>import
658 qualified</literal> declaration for every module in every
659 package, and every module currently loaded into GHCi. This
660 behaviour can be disabled with the flag <option>-fno-implicit-import-qualified</option><indexterm><primary><option>-fno-implicit-import-qualified</option></primary></indexterm>.</para>
664 <title>The <literal>:main</literal> and <literal>:run</literal> commands</title>
667 When a program is compiled and executed, it can use the
668 <literal>getArgs</literal> function to access the
669 command-line arguments.
670 However, we cannot simply pass the arguments to the
671 <literal>main</literal> function while we are testing in ghci,
672 as the <literal>main</literal> function doesn't take its
677 Instead, we can use the <literal>:main</literal> command.
678 This runs whatever <literal>main</literal> is in scope, with
679 any arguments being treated the same as command-line arguments,
684 Prelude> let main = System.Environment.getArgs >>= print
685 Prelude> :main foo bar
690 We can also quote arguments which contains characters like
691 spaces, and they are treated like Haskell strings, or we can
692 just use Haskell list syntax:
696 Prelude> :main foo "bar baz"
698 Prelude> :main ["foo", "bar baz"]
703 Finally, other functions can be called, either with the
704 <literal>-main-is</literal> flag or the <literal>:run</literal>
709 Prelude> let foo = putStrLn "foo" >> System.Environment.getArgs >>= print
710 Prelude> let bar = putStrLn "bar" >> System.Environment.getArgs >>= print
711 Prelude> :set -main-is foo
712 Prelude> :main foo "bar baz"
715 Prelude> :run bar ["foo", "bar baz"]
725 <title>The <literal>it</literal> variable</title>
726 <indexterm><primary><literal>it</literal></primary>
729 <para>Whenever an expression (or a non-binding statement, to be
730 precise) is typed at the prompt, GHCi implicitly binds its value
731 to the variable <literal>it</literal>. For example:</para>
738 <para>What actually happens is that GHCi typechecks the
739 expression, and if it doesn't have an <literal>IO</literal> type,
740 then it transforms it as follows: an expression
741 <replaceable>e</replaceable> turns into
743 let it = <replaceable>e</replaceable>;
746 which is then run as an IO-action.</para>
748 <para>Hence, the original expression must have a type which is an
749 instance of the <literal>Show</literal> class, or GHCi will
755 <interactive>:1:0:
756 No instance for (Show (a -> a))
757 arising from use of `print' at <interactive>:1:0-1
758 Possible fix: add an instance declaration for (Show (a -> a))
759 In the expression: print it
760 In a 'do' expression: print it
763 <para>The error message contains some clues as to the
764 transformation happening internally.</para>
766 <para>If the expression was instead of type <literal>IO a</literal> for
767 some <literal>a</literal>, then <literal>it</literal> will be
768 bound to the result of the <literal>IO</literal> computation,
769 which is of type <literal>a</literal>. eg.:</para>
771 Prelude> Time.getClockTime
772 Wed Mar 14 12:23:13 GMT 2001
774 Wed Mar 14 12:23:13 GMT 2001
777 <para>The corresponding translation for an IO-typed
778 <replaceable>e</replaceable> is
780 it <- <replaceable>e</replaceable>
784 <para>Note that <literal>it</literal> is shadowed by the new
785 value each time you evaluate a new expression, and the old value
786 of <literal>it</literal> is lost.</para>
790 <sect2 id="extended-default-rules">
791 <title>Type defaulting in GHCi</title>
792 <indexterm><primary>Type default</primary></indexterm>
793 <indexterm><primary><literal>Show</literal> class</primary></indexterm>
795 Consider this GHCi session:
799 What should GHCi do? Strictly speaking, the program is ambiguous. <literal>show (reverse [])</literal>
800 (which is what GHCi computes here) has type <literal>Show a => a</literal> and how that displays depends
801 on the type <literal>a</literal>. For example:
803 ghci> (reverse []) :: String
805 ghci> (reverse []) :: [Int]
808 However, it is tiresome for the user to have to specify the type, so GHCi extends Haskell's type-defaulting
809 rules (Section 4.3.4 of the Haskell 98 Report (Revised)) as follows. The
810 standard rules take each group of constraints <literal>(C1 a, C2 a, ..., Cn
811 a)</literal> for each type variable <literal>a</literal>, and defaults the
816 The type variable <literal>a</literal> appears in no
822 All the classes <literal>Ci</literal> are standard.
827 At least one of the classes <literal>Ci</literal> is
832 At the GHCi prompt, or with GHC if the
833 <literal>-XExtendedDefaultRules</literal> flag is given,
834 the following additional differences apply:
838 Rule 2 above is relaxed thus:
839 <emphasis>All</emphasis> of the classes
840 <literal>Ci</literal> are single-parameter type classes.
845 Rule 3 above is relaxed this:
846 At least one of the classes <literal>Ci</literal> is
847 numeric, <emphasis>or is <literal>Show</literal>,
848 <literal>Eq</literal>, or
849 <literal>Ord</literal></emphasis>.
854 The unit type <literal>()</literal> is added to the
855 start of the standard list of types which are tried when
856 doing type defaulting.
860 The last point means that, for example, this program:
867 def :: (Num a, Enum a) => a
870 prints <literal>()</literal> rather than <literal>0</literal> as the
871 type is defaulted to <literal>()</literal> rather than
872 <literal>Integer</literal>.
875 The motivation for the change is that it means <literal>IO a</literal>
876 actions default to <literal>IO ()</literal>, which in turn means that
877 ghci won't try to print a result when running them. This is
878 particularly important for <literal>printf</literal>, which has an
879 instance that returns <literal>IO a</literal>.
880 However, it is only able to return
881 <literal>undefined</literal>
882 (the reason for the instance having this type is so that printf
883 doesn't require extensions to the class system), so if the type defaults to
884 <literal>Integer</literal> then ghci gives an error when running a
890 <sect1 id="ghci-debugger">
891 <title>The GHCi Debugger</title>
892 <indexterm><primary>debugger</primary><secondary>in GHCi</secondary>
895 <para>GHCi contains a simple imperative-style debugger in which you can
896 stop a running computation in order to examine the values of
897 variables. The debugger is integrated into GHCi, and is turned on by
898 default: no flags are required to enable the debugging
899 facilities. There is one major restriction: breakpoints and
900 single-stepping are only available in interpreted modules;
901 compiled code is invisible to the debugger<footnote><para>Note that packages
902 only contain compiled code, so debugging a package requires
903 finding its source and loading that directly.</para></footnote>.</para>
905 <para>The debugger provides the following:
908 <para>The ability to set a <firstterm>breakpoint</firstterm> on a
909 function definition or expression in the program. When the function
910 is called, or the expression evaluated, GHCi suspends
911 execution and returns to the prompt, where you can inspect the
912 values of local variables before continuing with the
916 <para>Execution can be <firstterm>single-stepped</firstterm>: the
917 evaluator will suspend execution approximately after every
918 reduction, allowing local variables to be inspected. This is
919 equivalent to setting a breakpoint at every point in the
923 <para>Execution can take place in <firstterm>tracing
924 mode</firstterm>, in which the evaluator remembers each
925 evaluation step as it happens, but doesn't suspend execution until
926 an actual breakpoint is reached. When this happens, the history of
927 evaluation steps can be inspected.</para>
930 <para>Exceptions (e.g. pattern matching failure and
931 <literal>error</literal>) can be treated as breakpoints, to help
932 locate the source of an exception in the program.</para>
937 <para>There is currently no support for obtaining a “stack
938 trace”, but the tracing and history features provide a
939 useful second-best, which will often be enough to establish the
940 context of an error. For instance, it is possible to break
941 automatically when an exception is thrown, even if it is thrown
942 from within compiled code (see <xref
943 linkend="ghci-debugger-exceptions" />).</para>
945 <sect2 id="breakpoints">
946 <title>Breakpoints and inspecting variables</title>
948 <para>Let's use quicksort as a running example. Here's the code:</para>
952 qsort (a:as) = qsort left ++ [a] ++ qsort right
953 where (left,right) = (filter (<=a) as, filter (>a) as)
955 main = print (qsort [8, 4, 0, 3, 1, 23, 11, 18])
958 <para>First, load the module into GHCi:</para>
962 [1 of 1] Compiling Main ( qsort.hs, interpreted )
963 Ok, modules loaded: Main.
967 <para>Now, let's set a breakpoint on the right-hand-side of the second
968 equation of qsort:</para>
972 Breakpoint 0 activated at qsort.hs:2:15-46
976 <para>The command <literal>:break 2</literal> sets a breakpoint on line
977 2 of the most recently-loaded module, in this case
978 <literal>qsort.hs</literal>. Specifically, it picks the
979 leftmost complete subexpression on that line on which to set the
980 breakpoint, which in this case is the expression
981 <literal>(qsort left ++ [a] ++ qsort right)</literal>.</para>
983 <para>Now, we run the program:</para>
987 Stopped at qsort.hs:2:15-46
992 [qsort.hs:2:15-46] *Main>
995 <para>Execution has stopped at the breakpoint. The prompt has changed to
996 indicate that we are currently stopped at a breakpoint, and the location:
997 <literal>[qsort.hs:2:15-46]</literal>. To further clarify the
998 location, we can use the <literal>:list</literal> command:</para>
1001 [qsort.hs:2:15-46] *Main> :list
1003 2 qsort (a:as) = qsort left ++ [a] ++ qsort right
1004 3 where (left,right) = (filter (<=a) as, filter (>a) as)
1007 <para>The <literal>:list</literal> command lists the source code around
1008 the current breakpoint. If your output device supports it, then GHCi
1009 will highlight the active subexpression in bold.</para>
1011 <para>GHCi has provided bindings for the free variables<footnote><para>We
1012 originally provided bindings for all variables in scope, rather
1014 the free variables of the expression, but found that this affected
1015 performance considerably, hence the current restriction to just the
1016 free variables.</para>
1017 </footnote> of the expression
1019 breakpoint was placed (<literal>a</literal>, <literal>left</literal>,
1020 <literal>right</literal>), and additionally a binding for the result of
1021 the expression (<literal>_result</literal>). These variables are just
1022 like other variables that you might define in GHCi; you
1023 can use them in expressions that you type at the prompt, you can ask
1024 for their types with <literal>:type</literal>, and so on. There is one
1025 important difference though: these variables may only have partial
1026 types. For example, if we try to display the value of
1027 <literal>left</literal>:</para>
1030 [qsort.hs:2:15-46] *Main> left
1032 <interactive>:1:0:
1033 Ambiguous type variable `a' in the constraint:
1034 `Show a' arising from a use of `print' at <interactive>:1:0-3
1035 Cannot resolve unknown runtime types: a
1036 Use :print or :force to determine these types
1039 <para>This is because <literal>qsort</literal> is a polymorphic function,
1040 and because GHCi does not carry type information at runtime, it cannot
1041 determine the runtime types of free variables that involve type
1042 variables. Hence, when you ask to display <literal>left</literal> at
1043 the prompt, GHCi can't figure out which instance of
1044 <literal>Show</literal> to use, so it emits the type error above.</para>
1046 <para>Fortunately, the debugger includes a generic printing command,
1047 <literal>:print</literal>, which can inspect the actual runtime value of a
1048 variable and attempt to reconstruct its type. If we try it on
1049 <literal>left</literal>:</para>
1052 [qsort.hs:2:15-46] *Main> :set -fprint-evld-with-show
1053 [qsort.hs:2:15-46] *Main> :print left
1057 <para>This isn't particularly enlightening. What happened is that
1058 <literal>left</literal> is bound to an unevaluated computation (a
1059 suspension, or <firstterm>thunk</firstterm>), and
1060 <literal>:print</literal> does not force any evaluation. The idea is
1061 that <literal>:print</literal> can be used to inspect values at a
1062 breakpoint without any unfortunate side effects. It won't force any
1063 evaluation, which could cause the program to give a different answer
1064 than it would normally, and hence it won't cause any exceptions to be
1065 raised, infinite loops, or further breakpoints to be triggered (see
1066 <xref linkend="nested-breakpoints" />).
1067 Rather than forcing thunks, <literal>:print</literal>
1068 binds each thunk to a fresh variable beginning with an
1069 underscore, in this case
1070 <literal>_t1</literal>.</para>
1072 <para>The flag <literal>-fprint-evld-with-show</literal> instructs
1073 <literal>:print</literal> to reuse
1074 available <literal>Show</literal> instances when possible. This happens
1075 only when the contents of the variable being inspected
1076 are completely evaluated.</para>
1079 <para>If we aren't concerned about preserving the evaluatedness of a
1080 variable, we can use <literal>:force</literal> instead of
1081 <literal>:print</literal>. The <literal>:force</literal> command
1082 behaves exactly like <literal>:print</literal>, except that it forces
1083 the evaluation of any thunks it encounters:</para>
1086 [qsort.hs:2:15-46] *Main> :force left
1090 <para>Now, since <literal>:force</literal> has inspected the runtime
1091 value of <literal>left</literal>, it has reconstructed its type. We
1092 can see the results of this type reconstruction:</para>
1095 [qsort.hs:2:15-46] *Main> :show bindings
1096 _result :: [Integer]
1103 <para>Not only do we now know the type of <literal>left</literal>, but
1104 all the other partial types have also been resolved. So we can ask
1105 for the value of <literal>a</literal>, for example:</para>
1108 [qsort.hs:2:15-46] *Main> a
1112 <para>You might find it useful to use Haskell's
1113 <literal>seq</literal> function to evaluate individual thunks rather
1114 than evaluating the whole expression with <literal>:force</literal>.
1118 [qsort.hs:2:15-46] *Main> :print right
1119 right = (_t1::[Integer])
1120 [qsort.hs:2:15-46] *Main> seq _t1 ()
1122 [qsort.hs:2:15-46] *Main> :print right
1123 right = 23 : (_t2::[Integer])
1126 <para>We evaluated only the <literal>_t1</literal> thunk, revealing the
1127 head of the list, and the tail is another thunk now bound to
1128 <literal>_t2</literal>. The <literal>seq</literal> function is a
1129 little inconvenient to use here, so you might want to use
1130 <literal>:def</literal> to make a nicer interface (left as an exercise
1131 for the reader!).</para>
1133 <para>Finally, we can continue the current execution:</para>
1136 [qsort.hs:2:15-46] *Main> :continue
1137 Stopped at qsort.hs:2:15-46
1142 [qsort.hs:2:15-46] *Main>
1145 <para>The execution continued at the point it previously stopped, and has
1146 now stopped at the breakpoint for a second time.</para>
1149 <sect3 id="setting-breakpoints">
1150 <title>Setting breakpoints</title>
1152 <para>Breakpoints can be set in various ways. Perhaps the easiest way to
1153 set a breakpoint is to name a top-level function:</para>
1156 :break <replaceable>identifier</replaceable>
1159 <para>Where <replaceable>identifier</replaceable> names any top-level
1160 function in an interpreted module currently loaded into GHCi (qualified
1161 names may be used). The breakpoint will be set on the body of the
1162 function, when it is fully applied but before any pattern matching has
1165 <para>Breakpoints can also be set by line (and optionally column)
1169 :break <replaceable>line</replaceable>
1170 :break <replaceable>line</replaceable> <replaceable>column</replaceable>
1171 :break <replaceable>module</replaceable> <replaceable>line</replaceable>
1172 :break <replaceable>module</replaceable> <replaceable>line</replaceable> <replaceable>column</replaceable>
1175 <para>When a breakpoint is set on a particular line, GHCi sets the
1177 leftmost subexpression that begins and ends on that line. If two
1178 complete subexpressions start at the same
1179 column, the longest one is picked. If there is no complete
1180 subexpression on the line, then the leftmost expression starting on
1181 the line is picked, and failing that the rightmost expression that
1182 partially or completely covers the line.</para>
1184 <para>When a breakpoint is set on a particular line and column, GHCi
1185 picks the smallest subexpression that encloses that location on which
1186 to set the breakpoint. Note: GHC considers the TAB character to have a
1187 width of 1, wherever it occurs; in other words it counts
1188 characters, rather than columns. This matches what some editors do,
1189 and doesn't match others. The best advice is to avoid tab
1190 characters in your source code altogether (see
1191 <option>-fwarn-tabs</option> in <xref linkend="options-sanity"
1194 <para>If the module is omitted, then the most recently-loaded module is
1197 <para>Not all subexpressions are potential breakpoint locations. Single
1198 variables are typically not considered to be breakpoint locations
1199 (unless the variable is the right-hand-side of a function definition,
1200 lambda, or case alternative). The rule of thumb is that all redexes
1201 are breakpoint locations, together with the bodies of functions,
1202 lambdas, case alternatives and binding statements. There is normally
1203 no breakpoint on a let expression, but there will always be a
1204 breakpoint on its body, because we are usually interested in inspecting
1205 the values of the variables bound by the let.</para>
1209 <title>Listing and deleting breakpoints</title>
1211 <para>The list of breakpoints currently enabled can be displayed using
1212 <literal>:show breaks</literal>:</para>
1215 [0] Main qsort.hs:1:11-12
1216 [1] Main qsort.hs:2:15-46
1219 <para>To delete a breakpoint, use the <literal>:delete</literal>
1220 command with the number given in the output from <literal>:show breaks</literal>:</para>
1225 [1] Main qsort.hs:2:15-46
1228 <para>To delete all breakpoints at once, use <literal>:delete *</literal>.</para>
1233 <sect2 id="single-stepping">
1234 <title>Single-stepping</title>
1236 <para>Single-stepping is a great way to visualise the execution of your
1237 program, and it is also a useful tool for identifying the source of a
1238 bug. GHCi offers two variants of stepping. Use
1239 <literal>:step</literal> to enable all the
1240 breakpoints in the program, and execute until the next breakpoint is
1241 reached. Use <literal>:steplocal</literal> to limit the set
1242 of enabled breakpoints to those in the current top level function.
1243 Similarly, use <literal>:stepmodule</literal> to single step only on
1244 breakpoints contained in the current module.
1249 Stopped at qsort.hs:5:7-47
1253 <para>The command <literal>:step
1254 <replaceable>expr</replaceable></literal> begins the evaluation of
1255 <replaceable>expr</replaceable> in single-stepping mode. If
1256 <replaceable>expr</replaceable> is omitted, then it single-steps from
1257 the current breakpoint. <literal>:stepover</literal>
1258 works similarly.</para>
1260 <para>The <literal>:list</literal> command is particularly useful when
1261 single-stepping, to see where you currently are:</para>
1264 [qsort.hs:5:7-47] *Main> :list
1266 5 main = print (qsort [8, 4, 0, 3, 1, 23, 11, 18])
1268 [qsort.hs:5:7-47] *Main>
1271 <para>In fact, GHCi provides a way to run a command when a breakpoint is
1272 hit, so we can make it automatically do
1273 <literal>:list</literal>:</para>
1276 [qsort.hs:5:7-47] *Main> :set stop :list
1277 [qsort.hs:5:7-47] *Main> :step
1278 Stopped at qsort.hs:5:14-46
1279 _result :: [Integer]
1281 5 main = print (qsort [8, 4, 0, 3, 1, 23, 11, 18])
1283 [qsort.hs:5:14-46] *Main>
1287 <sect2 id="nested-breakpoints">
1288 <title>Nested breakpoints</title>
1289 <para>When GHCi is stopped at a breakpoint, and an expression entered at
1290 the prompt triggers a
1291 second breakpoint, the new breakpoint becomes the “current”
1292 one, and the old one is saved on a stack. An arbitrary number of
1293 breakpoint contexts can be built up in this way. For example:</para>
1296 [qsort.hs:2:15-46] *Main> :st qsort [1,3]
1297 Stopped at qsort.hs:(1,0)-(3,55)
1299 ... [qsort.hs:(1,0)-(3,55)] *Main>
1302 <para>While stopped at the breakpoint on line 2 that we set earlier, we
1303 started a new evaluation with <literal>:step qsort [1,3]</literal>.
1304 This new evaluation stopped after one step (at the definition of
1305 <literal>qsort</literal>). The prompt has changed, now prefixed with
1306 <literal>...</literal>, to indicate that there are saved breakpoints
1307 beyond the current one. To see the stack of contexts, use
1308 <literal>:show context</literal>:</para>
1311 ... [qsort.hs:(1,0)-(3,55)] *Main> :show context
1313 Stopped at qsort.hs:2:15-46
1315 Stopped at qsort.hs:(1,0)-(3,55)
1316 ... [qsort.hs:(1,0)-(3,55)] *Main>
1319 <para>To abandon the current evaluation, use
1320 <literal>:abandon</literal>:</para>
1323 ... [qsort.hs:(1,0)-(3,55)] *Main> :abandon
1324 [qsort.hs:2:15-46] *Main> :abandon
1329 <sect2 id="ghci-debugger-result">
1330 <title>The <literal>_result</literal> variable</title>
1331 <para>When stopped at a breakpoint or single-step, GHCi binds the
1332 variable <literal>_result</literal> to the value of the currently
1333 active expression. The value of <literal>_result</literal> is
1334 presumably not available yet, because we stopped its evaluation, but it
1335 can be forced: if the type is known and showable, then just entering
1336 <literal>_result</literal> at the prompt will show it. However,
1337 there's one caveat to doing this: evaluating <literal>_result</literal>
1338 will be likely to trigger further breakpoints, starting with the
1339 breakpoint we are currently stopped at (if we stopped at a real
1340 breakpoint, rather than due to <literal>:step</literal>). So it will
1341 probably be necessary to issue a <literal>:continue</literal>
1342 immediately when evaluating <literal>_result</literal>. Alternatively,
1343 you can use <literal>:force</literal> which ignores breakpoints.</para>
1346 <sect2 id="tracing">
1347 <title>Tracing and history</title>
1349 <para>A question that we often want to ask when debugging a program is
1350 “how did I get here?”. Traditional imperative debuggers
1351 usually provide some kind of stack-tracing feature that lets you see
1352 the stack of active function calls (sometimes called the “lexical
1353 call stack”), describing a path through the code
1354 to the current location. Unfortunately this is hard to provide in
1355 Haskell, because execution proceeds on a demand-driven basis, rather
1356 than a depth-first basis as in strict languages. The
1357 “stack“ in GHC's execution engine bears little
1358 resemblance to the lexical call stack. Ideally GHCi would maintain a
1359 separate lexical call stack in addition to the dynamic call stack, and
1360 in fact this is exactly
1361 what our profiling system does (<xref linkend="profiling" />), and what
1362 some other Haskell debuggers do. For the time being, however, GHCi
1363 doesn't maintain a lexical call stack (there are some technical
1364 challenges to be overcome). Instead, we provide a way to backtrack from a
1365 breakpoint to previous evaluation steps: essentially this is like
1366 single-stepping backwards, and should in many cases provide enough
1367 information to answer the “how did I get here?”
1370 <para>To use tracing, evaluate an expression with the
1371 <literal>:trace</literal> command. For example, if we set a breakpoint
1372 on the base case of <literal>qsort</literal>:</para>
1375 *Main> :list qsort
1377 2 qsort (a:as) = qsort left ++ [a] ++ qsort right
1378 3 where (left,right) = (filter (<=a) as, filter (>a) as)
1381 Breakpoint 1 activated at qsort.hs:1:11-12
1385 <para>and then run a small <literal>qsort</literal> with
1389 *Main> :trace qsort [3,2,1]
1390 Stopped at qsort.hs:1:11-12
1392 [qsort.hs:1:11-12] *Main>
1395 <para>We can now inspect the history of evaluation steps:</para>
1398 [qsort.hs:1:11-12] *Main> :hist
1399 -1 : qsort.hs:3:24-38
1400 -2 : qsort.hs:3:23-55
1401 -3 : qsort.hs:(1,0)-(3,55)
1402 -4 : qsort.hs:2:15-24
1403 -5 : qsort.hs:2:15-46
1404 -6 : qsort.hs:3:24-38
1405 -7 : qsort.hs:3:23-55
1406 -8 : qsort.hs:(1,0)-(3,55)
1407 -9 : qsort.hs:2:15-24
1408 -10 : qsort.hs:2:15-46
1409 -11 : qsort.hs:3:24-38
1410 -12 : qsort.hs:3:23-55
1411 -13 : qsort.hs:(1,0)-(3,55)
1412 -14 : qsort.hs:2:15-24
1413 -15 : qsort.hs:2:15-46
1414 -16 : qsort.hs:(1,0)-(3,55)
1415 <end of history>
1418 <para>To examine one of the steps in the history, use
1419 <literal>:back</literal>:</para>
1422 [qsort.hs:1:11-12] *Main> :back
1423 Logged breakpoint at qsort.hs:3:24-38
1427 [-1: qsort.hs:3:24-38] *Main>
1430 <para>Note that the local variables at each step in the history have been
1431 preserved, and can be examined as usual. Also note that the prompt has
1432 changed to indicate that we're currently examining the first step in
1433 the history: <literal>-1</literal>. The command
1434 <literal>:forward</literal> can be used to traverse forward in the
1437 <para>The <literal>:trace</literal> command can be used with or without
1438 an expression. When used without an expression, tracing begins from
1439 the current breakpoint, just like <literal>:step</literal>.</para>
1441 <para>The history is only available when
1442 using <literal>:trace</literal>; the reason for this is we found that
1443 logging each breakpoint in the history cuts performance by a factor of
1444 2 or more. GHCi remembers the last 50 steps in the history (perhaps in
1445 the future we'll make this configurable).</para>
1448 <sect2 id="ghci-debugger-exceptions">
1449 <title>Debugging exceptions</title>
1450 <para>Another common question that comes up when debugging is
1451 “where did this exception come from?”. Exceptions such as
1452 those raised by <literal>error</literal> or <literal>head []</literal>
1453 have no context information attached to them. Finding which
1454 particular call to <literal>head</literal> in your program resulted in
1455 the error can be a painstaking process, usually involving
1456 <literal>Debug.Trace.trace</literal>, or compiling with
1457 profiling and using <literal>+RTS -xc</literal> (see <xref
1458 linkend="prof-time-options" />).</para>
1460 <para>The GHCi debugger offers a way to hopefully shed some light on
1461 these errors quickly and without modifying or recompiling the source
1462 code. One way would be to set a breakpoint on the location in the
1463 source code that throws the exception, and then use
1464 <literal>:trace</literal> and <literal>:history</literal> to establish
1465 the context. However, <literal>head</literal> is in a library and
1466 we can't set a breakpoint on it directly. For this reason, GHCi
1467 provides the flags <literal>-fbreak-on-exception</literal> which causes
1468 the evaluator to stop when an exception is thrown, and <literal>
1469 -fbreak-on-error</literal>, which works similarly but stops only on
1470 uncaught exceptions. When stopping at an exception, GHCi will act
1471 just as it does when a breakpoint is hit, with the deviation that it
1472 will not show you any source code location. Due to this, these
1473 commands are only really useful in conjunction with
1474 <literal>:trace</literal>, in order to log the steps leading up to the
1475 exception. For example:</para>
1478 *Main> :set -fbreak-on-exception
1479 *Main> :trace qsort ("abc" ++ undefined)
1480 "Stopped at <exception thrown>
1482 [<exception thrown>] *Main> :hist
1483 -1 : qsort.hs:3:24-38
1484 -2 : qsort.hs:3:23-55
1485 -3 : qsort.hs:(1,0)-(3,55)
1486 -4 : qsort.hs:2:15-24
1487 -5 : qsort.hs:2:15-46
1488 -6 : qsort.hs:(1,0)-(3,55)
1489 <end of history>
1490 [<exception thrown>] *Main> :back
1491 Logged breakpoint at qsort.hs:3:24-38
1495 [-1: qsort.hs:3:24-38] *Main> :force as
1496 *** Exception: Prelude.undefined
1497 [-1: qsort.hs:3:24-38] *Main> :print as
1498 as = 'b' : 'c' : (_t1::[Char])
1501 <para>The exception itself is bound to a new variable,
1502 <literal>_exception</literal>.</para>
1504 <para>Breaking on exceptions is particularly useful for finding out what
1505 your program was doing when it was in an infinite loop. Just hit
1506 Control-C, and examine the history to find out what was going
1510 <sect2><title>Example: inspecting functions</title>
1512 It is possible to use the debugger to examine function values.
1513 When we are at a breakpoint and a function is in scope, the debugger
1515 you the source code for it; however, it is possible to get some
1516 information by applying it to some arguments and observing the result.
1520 The process is slightly complicated when the binding is polymorphic.
1521 We show the process by means of an example.
1522 To keep things simple, we will use the well known <literal>map</literal> function:
1524 import Prelude hiding (map)
1526 map :: (a->b) -> [a] -> [b]
1528 map f (x:xs) = f x : map f xs
1533 We set a breakpoint on <literal>map</literal>, and call it.
1536 Breakpoint 0 activated at map.hs:5:15-28
1537 *Main> map Just [1..5]
1538 Stopped at map.hs:(4,0)-(5,12)
1544 GHCi tells us that, among other bindings, <literal>f</literal> is in scope.
1545 However, its type is not fully known yet,
1546 and thus it is not possible to apply it to any
1547 arguments. Nevertheless, observe that the type of its first argument is the
1548 same as the type of <literal>x</literal>, and its result type is shared
1549 with <literal>_result</literal>.
1553 As we demonstrated earlier (<xref linkend="breakpoints" />), the
1554 debugger has some intelligence built-in to update the type of
1555 <literal>f</literal> whenever the types of <literal>x</literal> or
1556 <literal>_result</literal> are discovered. So what we do in this
1558 force <literal>x</literal> a bit, in order to recover both its type
1559 and the argument part of <literal>f</literal>.
1567 We can check now that as expected, the type of <literal>x</literal>
1568 has been reconstructed, and with it the
1569 type of <literal>f</literal> has been too:</para>
1577 From here, we can apply f to any argument of type Integer and observe
1585 Ambiguous type variable `b' in the constraint:
1586 `Show b' arising from a use of `print' at <interactive>:1:0
1598 f :: Integer -> Maybe Integer
1602 [Just 1, Just 2, Just 3, Just 4, Just 5]
1604 In the first application of <literal>f</literal>, we had to do
1605 some more type reconstruction
1606 in order to recover the result type of <literal>f</literal>.
1607 But after that, we are free to use
1608 <literal>f</literal> normally.
1612 <sect2><title>Limitations</title>
1615 <para>When stopped at a breakpoint, if you try to evaluate a variable
1616 that is already under evaluation, the second evaluation will hang.
1618 that GHC knows the variable is under evaluation, so the new
1619 evaluation just waits for the result before continuing, but of
1620 course this isn't going to happen because the first evaluation is
1621 stopped at a breakpoint. Control-C can interrupt the hung
1622 evaluation and return to the prompt.</para>
1623 <para>The most common way this can happen is when you're evaluating a
1624 CAF (e.g. main), stop at a breakpoint, and ask for the value of the
1625 CAF at the prompt again.</para>
1628 Implicit parameters (see <xref linkend="implicit-parameters"/>) are only available
1629 at the scope of a breakpoint if there is an explicit type signature.
1636 <sect1 id="ghci-invocation">
1637 <title>Invoking GHCi</title>
1638 <indexterm><primary>invoking</primary><secondary>GHCi</secondary></indexterm>
1639 <indexterm><primary><option>––interactive</option></primary></indexterm>
1641 <para>GHCi is invoked with the command <literal>ghci</literal> or
1642 <literal>ghc ––interactive</literal>. One or more modules or
1643 filenames can also be specified on the command line; this
1644 instructs GHCi to load the specified modules or filenames (and all
1645 the modules they depend on), just as if you had said
1646 <literal>:load <replaceable>modules</replaceable></literal> at the
1647 GHCi prompt (see <xref linkend="ghci-commands" />). For example, to
1648 start GHCi and load the program whose topmost module is in the
1649 file <literal>Main.hs</literal>, we could say:</para>
1655 <para>Most of the command-line options accepted by GHC (see <xref
1656 linkend="using-ghc"/>) also make sense in interactive mode. The ones
1657 that don't make sense are mostly obvious.</para>
1660 <title>Packages</title>
1661 <indexterm><primary>packages</primary><secondary>with GHCi</secondary></indexterm>
1663 <para>Most packages (see <xref linkend="using-packages"/>) are
1664 available without needing to specify any extra flags at all:
1665 they will be automatically loaded the first time they are
1668 <para>For hidden packages, however, you need to request the
1669 package be loaded by using the <literal>-package</literal> flag:</para>
1672 $ ghci -package readline
1673 GHCi, version 6.8.1: http://www.haskell.org/ghc/ :? for help
1674 Loading package base ... linking ... done.
1675 Loading package readline-1.0 ... linking ... done.
1679 <para>The following command works to load new packages into a
1680 running GHCi:</para>
1683 Prelude> :set -package <replaceable>name</replaceable>
1686 <para>But note that doing this will cause all currently loaded
1687 modules to be unloaded, and you'll be dumped back into the
1688 <literal>Prelude</literal>.</para>
1692 <title>Extra libraries</title>
1693 <indexterm><primary>libraries</primary><secondary>with GHCi</secondary></indexterm>
1695 <para>Extra libraries may be specified on the command line using
1696 the normal <literal>-l<replaceable>lib</replaceable></literal>
1697 option. (The term <emphasis>library</emphasis> here refers to
1698 libraries of foreign object code; for using libraries of Haskell
1699 source code, see <xref linkend="ghci-modules-filenames"/>.) For
1700 example, to load the “m” library:</para>
1706 <para>On systems with <literal>.so</literal>-style shared
1707 libraries, the actual library loaded will the
1708 <filename>lib<replaceable>lib</replaceable>.so</filename>. GHCi
1709 searches the following places for libraries, in this order:</para>
1713 <para>Paths specified using the
1714 <literal>-L<replaceable>path</replaceable></literal>
1715 command-line option,</para>
1718 <para>the standard library search path for your system,
1719 which on some systems may be overridden by setting the
1720 <literal>LD_LIBRARY_PATH</literal> environment
1725 <para>On systems with <literal>.dll</literal>-style shared
1726 libraries, the actual library loaded will be
1727 <filename><replaceable>lib</replaceable>.dll</filename>. Again,
1728 GHCi will signal an error if it can't find the library.</para>
1730 <para>GHCi can also load plain object files
1731 (<literal>.o</literal> or <literal>.obj</literal> depending on
1732 your platform) from the command-line. Just add the name the
1733 object file to the command line.</para>
1735 <para>Ordering of <option>-l</option> options matters: a library
1736 should be mentioned <emphasis>before</emphasis> the libraries it
1737 depends on (see <xref linkend="options-linker"/>).</para>
1742 <sect1 id="ghci-commands">
1743 <title>GHCi commands</title>
1745 <para>GHCi commands all begin with
1746 ‘<literal>:</literal>’ and consist of a single command
1747 name followed by zero or more parameters. The command name may be
1748 abbreviated, with ambiguities being resolved in favour of the more
1749 commonly used commands.</para>
1754 <literal>:abandon</literal>
1755 <indexterm><primary><literal>:abandon</literal></primary></indexterm>
1758 <para>Abandons the current evaluation (only available when stopped at
1759 a breakpoint).</para>
1765 <literal>:add</literal> <replaceable>module</replaceable> ...
1766 <indexterm><primary><literal>:add</literal></primary></indexterm>
1769 <para>Add <replaceable>module</replaceable>(s) to the
1770 current <firstterm>target set</firstterm>, and perform a
1777 <literal>:back</literal>
1778 <indexterm><primary><literal>:back</literal></primary></indexterm>
1781 <para>Travel back one step in the history. See <xref
1782 linkend="tracing" />. See also:
1783 <literal>:trace</literal>, <literal>:history</literal>,
1784 <literal>:forward</literal>.</para>
1790 <literal>:break [<replaceable>identifier</replaceable> |
1791 [<replaceable>module</replaceable>] <replaceable>line</replaceable>
1792 [<replaceable>column</replaceable>]]</literal>
1794 <indexterm><primary><literal>:break</literal></primary></indexterm>
1796 <para>Set a breakpoint on the specified function or line and
1797 column. See <xref linkend="setting-breakpoints" />.</para>
1803 <literal>:browse</literal><optional><literal>!</literal></optional> <optional><optional><literal>*</literal></optional><replaceable>module</replaceable></optional> ...
1804 <indexterm><primary><literal>:browse</literal></primary></indexterm>
1807 <para>Displays the identifiers defined by the module
1808 <replaceable>module</replaceable>, which must be either
1809 loaded into GHCi or be a member of a package. If
1810 <replaceable>module</replaceable> is omitted, the most
1811 recently-loaded module is used.</para>
1813 <para>If the <literal>*</literal> symbol is placed before
1814 the module name, then <emphasis>all</emphasis> the
1815 identifiers in scope in <replaceable>module</replaceable> are
1816 shown; otherwise the list is limited to the exports of
1817 <replaceable>module</replaceable>. The
1818 <literal>*</literal>-form is only available for modules
1819 which are interpreted; for compiled modules (including
1820 modules from packages) only the non-<literal>*</literal>
1821 form of <literal>:browse</literal> is available.
1822 If the <literal>!</literal> symbol is appended to the
1823 command, data constructors and class methods will be
1824 listed individually, otherwise, they will only be listed
1825 in the context of their data type or class declaration.
1826 The <literal>!</literal>-form also annotates the listing
1827 with comments giving possible imports for each group of
1830 Prelude> :browse! Data.Maybe
1831 -- not currently imported
1832 Data.Maybe.catMaybes :: [Maybe a] -> [a]
1833 Data.Maybe.fromJust :: Maybe a -> a
1834 Data.Maybe.fromMaybe :: a -> Maybe a -> a
1835 Data.Maybe.isJust :: Maybe a -> Bool
1836 Data.Maybe.isNothing :: Maybe a -> Bool
1837 Data.Maybe.listToMaybe :: [a] -> Maybe a
1838 Data.Maybe.mapMaybe :: (a -> Maybe b) -> [a] -> [b]
1839 Data.Maybe.maybeToList :: Maybe a -> [a]
1840 -- imported via Prelude
1841 Just :: a -> Maybe a
1842 data Maybe a = Nothing | Just a
1844 maybe :: b -> (a -> b) -> Maybe a -> b
1847 This output shows that, in the context of the current session, in the scope
1848 of <literal>Prelude</literal>, the first group of items from
1849 <literal>Data.Maybe</literal> have not been imported (but are available in
1850 fully qualified form in the GHCi session - see <xref
1851 linkend="ghci-scope"/>), whereas the second group of items have been
1852 imported via <literal>Prelude</literal> and are therefore available either
1853 unqualified, or with a <literal>Prelude.</literal> qualifier.
1860 <literal>:cd</literal> <replaceable>dir</replaceable>
1861 <indexterm><primary><literal>:cd</literal></primary></indexterm>
1864 <para>Changes the current working directory to
1865 <replaceable>dir</replaceable>. A
1866 ‘<literal>˜</literal>’ symbol at the
1867 beginning of <replaceable>dir</replaceable> will be replaced
1868 by the contents of the environment variable
1869 <literal>HOME</literal>.</para>
1871 <para>NOTE: changing directories causes all currently loaded
1872 modules to be unloaded. This is because the search path is
1873 usually expressed using relative directories, and changing
1874 the search path in the middle of a session is not
1881 <literal>:cmd</literal> <replaceable>expr</replaceable>
1882 <indexterm><primary><literal>:cmd</literal></primary></indexterm>
1885 <para>Executes <replaceable>expr</replaceable> as a computation of
1886 type <literal>IO String</literal>, and then executes the resulting
1887 string as a list of GHCi commands. Multiple commands are separated
1888 by newlines. The <literal>:cmd</literal> command is useful with
1889 <literal>:def</literal> and <literal>:set stop</literal>.</para>
1895 <literal>:continue</literal>
1896 <indexterm><primary><literal>:continue</literal></primary></indexterm>
1898 <listitem><para>Continue the current evaluation, when stopped at a
1905 <literal>:ctags</literal> <optional><replaceable>filename</replaceable></optional>
1906 <literal>:etags</literal> <optional><replaceable>filename</replaceable></optional>
1907 <indexterm><primary><literal>:etags</literal></primary>
1909 <indexterm><primary><literal>:etags</literal></primary>
1913 <para>Generates a “tags” file for Vi-style editors
1914 (<literal>:ctags</literal>) or
1915 Emacs-style editors (<literal>:etags</literal>). If
1916 no filename is specified, the default <filename>tags</filename> or
1917 <filename>TAGS</filename> is
1918 used, respectively. Tags for all the functions, constructors and
1919 types in the currently loaded modules are created. All modules must
1920 be interpreted for these commands to work.</para>
1921 <para>See also <xref linkend="hasktags" />.</para>
1927 <literal>:def<optional>!</optional> <optional><replaceable>name</replaceable> <replaceable>expr</replaceable></optional></literal>
1928 <indexterm><primary><literal>:def</literal></primary></indexterm>
1931 <para><literal>:def</literal> is used to define new
1932 commands, or macros, in GHCi. The command
1933 <literal>:def</literal> <replaceable>name</replaceable>
1934 <replaceable>expr</replaceable> defines a new GHCi command
1935 <literal>:<replaceable>name</replaceable></literal>,
1936 implemented by the Haskell expression
1937 <replaceable>expr</replaceable>, which must have type
1938 <literal>String -> IO String</literal>. When
1939 <literal>:<replaceable>name</replaceable>
1940 <replaceable>args</replaceable></literal> is typed at the
1941 prompt, GHCi will run the expression
1942 <literal>(<replaceable>name</replaceable>
1943 <replaceable>args</replaceable>)</literal>, take the
1944 resulting <literal>String</literal>, and feed it back into
1945 GHCi as a new sequence of commands. Separate commands in
1946 the result must be separated by
1947 ‘<literal>\n</literal>’.</para>
1949 <para>That's all a little confusing, so here's a few
1950 examples. To start with, here's a new GHCi command which
1951 doesn't take any arguments or produce any results, it just
1952 outputs the current date & time:</para>
1955 Prelude> let date _ = Time.getClockTime >>= print >> return ""
1956 Prelude> :def date date
1958 Fri Mar 23 15:16:40 GMT 2001
1961 <para>Here's an example of a command that takes an argument.
1962 It's a re-implementation of <literal>:cd</literal>:</para>
1965 Prelude> let mycd d = Directory.setCurrentDirectory d >> return ""
1966 Prelude> :def mycd mycd
1970 <para>Or I could define a simple way to invoke
1971 “<literal>ghc ––make Main</literal>” in the
1972 current directory:</para>
1975 Prelude> :def make (\_ -> return ":! ghc ––make Main")
1978 <para>We can define a command that reads GHCi input from a
1979 file. This might be useful for creating a set of bindings
1980 that we want to repeatedly load into the GHCi session:</para>
1983 Prelude> :def . readFile
1984 Prelude> :. cmds.ghci
1987 <para>Notice that we named the command
1988 <literal>:.</literal>, by analogy with the
1989 ‘<literal>.</literal>’ Unix shell command that
1990 does the same thing.</para>
1992 <para>Typing <literal>:def</literal> on its own lists the
1993 currently-defined macros. Attempting to redefine an
1994 existing command name results in an error unless the
1995 <literal>:def!</literal> form is used, in which case the old
1996 command with that name is silently overwritten.</para>
2002 <literal>:delete * | <replaceable>num</replaceable> ...</literal>
2003 <indexterm><primary><literal>:delete</literal></primary></indexterm>
2006 <para>Delete one or more breakpoints by number (use <literal>:show
2007 breaks</literal> to see the number of each breakpoint). The
2008 <literal>*</literal> form deletes all the breakpoints.</para>
2014 <literal>:edit <optional><replaceable>file</replaceable></optional></literal>
2015 <indexterm><primary><literal>:edit</literal></primary></indexterm>
2018 <para>Opens an editor to edit the file
2019 <replaceable>file</replaceable>, or the most recently loaded
2020 module if <replaceable>file</replaceable> is omitted. The
2021 editor to invoke is taken from the <literal>EDITOR</literal>
2022 environment variable, or a default editor on your system if
2023 <literal>EDITOR</literal> is not set. You can change the
2024 editor using <literal>:set editor</literal>.</para>
2030 <literal>:etags</literal>
2033 <para>See <literal>:ctags</literal>.</para>
2039 <literal>:force <replaceable>identifier</replaceable> ...</literal>
2040 <indexterm><primary><literal>:force</literal></primary></indexterm>
2043 <para>Prints the value of <replaceable>identifier</replaceable> in
2044 the same way as <literal>:print</literal>. Unlike
2045 <literal>:print</literal>, <literal>:force</literal> evaluates each
2046 thunk that it encounters while traversing the value. This may
2047 cause exceptions or infinite loops, or further breakpoints (which
2048 are ignored, but displayed).</para>
2054 <literal>:forward</literal>
2055 <indexterm><primary><literal>:forward</literal></primary></indexterm>
2058 <para>Move forward in the history. See <xref
2059 linkend="tracing" />. See also:
2060 <literal>:trace</literal>, <literal>:history</literal>,
2061 <literal>:back</literal>.</para>
2067 <literal>:help</literal>
2068 <indexterm><primary><literal>:help</literal></primary></indexterm>
2071 <literal>:?</literal>
2072 <indexterm><primary><literal>:?</literal></primary></indexterm>
2075 <para>Displays a list of the available commands.</para>
2081 <literal>:</literal>
2082 <indexterm><primary><literal>:</literal></primary></indexterm>
2085 <para>Repeat the previous command.</para>
2092 <literal>:history [<replaceable>num</replaceable>]</literal>
2093 <indexterm><primary><literal>:history</literal></primary></indexterm>
2096 <para>Display the history of evaluation steps. With a number,
2097 displays that many steps (default: 20). For use with
2098 <literal>:trace</literal>; see <xref
2099 linkend="tracing" />.</para>
2105 <literal>:info</literal> <replaceable>name</replaceable> ...
2106 <indexterm><primary><literal>:info</literal></primary></indexterm>
2109 <para>Displays information about the given name(s). For
2110 example, if <replaceable>name</replaceable> is a class, then
2111 the class methods and their types will be printed; if
2112 <replaceable>name</replaceable> is a type constructor, then
2113 its definition will be printed; if
2114 <replaceable>name</replaceable> is a function, then its type
2115 will be printed. If <replaceable>name</replaceable> has
2116 been loaded from a source file, then GHCi will also display
2117 the location of its definition in the source.</para>
2118 <para>For types and classes, GHCi also summarises instances that
2119 mention them. To avoid showing irrelevant information, an instance
2120 is shown only if (a) its head mentions <replaceable>name</replaceable>,
2121 and (b) all the other things mentioned in the instance
2122 are in scope (either qualified or otherwise) as a result of
2123 a <literal>:load</literal> or <literal>:module</literal> commands. </para>
2129 <literal>:kind</literal> <replaceable>type</replaceable>
2130 <indexterm><primary><literal>:kind</literal></primary></indexterm>
2133 <para>Infers and prints the kind of
2134 <replaceable>type</replaceable>. The latter can be an arbitrary
2135 type expression, including a partial application of a type constructor,
2136 such as <literal>Either Int</literal>.</para>
2142 <literal>:load</literal> <replaceable>module</replaceable> ...
2143 <indexterm><primary><literal>:load</literal></primary></indexterm>
2146 <para>Recursively loads the specified
2147 <replaceable>module</replaceable>s, and all the modules they
2148 depend on. Here, each <replaceable>module</replaceable>
2149 must be a module name or filename, but may not be the name
2150 of a module in a package.</para>
2152 <para>All previously loaded modules, except package modules,
2153 are forgotten. The new set of modules is known as the
2154 <firstterm>target set</firstterm>. Note that
2155 <literal>:load</literal> can be used without any arguments
2156 to unload all the currently loaded modules and
2159 <para>After a <literal>:load</literal> command, the current
2160 context is set to:</para>
2164 <para><replaceable>module</replaceable>, if it was loaded
2165 successfully, or</para>
2168 <para>the most recently successfully loaded module, if
2169 any other modules were loaded as a result of the current
2170 <literal>:load</literal>, or</para>
2173 <para><literal>Prelude</literal> otherwise.</para>
2181 <literal>:main <replaceable>arg<subscript>1</subscript></replaceable> ... <replaceable>arg<subscript>n</subscript></replaceable></literal>
2182 <indexterm><primary><literal>:main</literal></primary></indexterm>
2186 When a program is compiled and executed, it can use the
2187 <literal>getArgs</literal> function to access the
2188 command-line arguments.
2189 However, we cannot simply pass the arguments to the
2190 <literal>main</literal> function while we are testing in ghci,
2191 as the <literal>main</literal> function doesn't take its
2196 Instead, we can use the <literal>:main</literal> command.
2197 This runs whatever <literal>main</literal> is in scope, with
2198 any arguments being treated the same as command-line arguments,
2203 Prelude> let main = System.Environment.getArgs >>= print
2204 Prelude> :main foo bar
2209 We can also quote arguments which contains characters like
2210 spaces, and they are treated like Haskell strings, or we can
2211 just use Haskell list syntax:
2215 Prelude> :main foo "bar baz"
2217 Prelude> :main ["foo", "bar baz"]
2222 Finally, other functions can be called, either with the
2223 <literal>-main-is</literal> flag or the <literal>:run</literal>
2228 Prelude> let foo = putStrLn "foo" >> System.Environment.getArgs >>= print
2229 Prelude> let bar = putStrLn "bar" >> System.Environment.getArgs >>= print
2230 Prelude> :set -main-is foo
2231 Prelude> :main foo "bar baz"
2234 Prelude> :run bar ["foo", "bar baz"]
2244 <literal>:module <optional>+|-</optional> <optional>*</optional><replaceable>mod<subscript>1</subscript></replaceable> ... <optional>*</optional><replaceable>mod<subscript>n</subscript></replaceable></literal>
2245 <indexterm><primary><literal>:module</literal></primary></indexterm>
2248 <literal>import <replaceable>mod</replaceable></literal>
2251 <para>Sets or modifies the current context for statements
2252 typed at the prompt. The form <literal>import
2253 <replaceable>mod</replaceable></literal> is equivalent to
2254 <literal>:module +<replaceable>mod</replaceable></literal>.
2255 See <xref linkend="ghci-scope"/> for
2256 more details.</para>
2262 <literal>:print </literal> <replaceable>names</replaceable> ...
2263 <indexterm><primary><literal>:print</literal></primary></indexterm>
2266 <para>Prints a value without forcing its evaluation.
2267 <literal>:print</literal> may be used on values whose types are
2268 unknown or partially known, which might be the case for local
2269 variables with polymorphic types at a breakpoint. While inspecting
2270 the runtime value, <literal>:print</literal> attempts to
2271 reconstruct the type of the value, and will elaborate the type in
2272 GHCi's environment if possible. If any unevaluated components
2273 (thunks) are encountered, then <literal>:print</literal> binds
2274 a fresh variable with a name beginning with <literal>_t</literal>
2275 to each thunk. See <xref linkend="breakpoints" /> for more
2276 information. See also the <literal>:sprint</literal> command,
2277 which works like <literal>:print</literal> but does not bind new
2284 <literal>:quit</literal>
2285 <indexterm><primary><literal>:quit</literal></primary></indexterm>
2288 <para>Quits GHCi. You can also quit by typing control-D
2289 at the prompt.</para>
2295 <literal>:reload</literal>
2296 <indexterm><primary><literal>:reload</literal></primary></indexterm>
2299 <para>Attempts to reload the current target set (see
2300 <literal>:load</literal>) if any of the modules in the set,
2301 or any dependent module, has changed. Note that this may
2302 entail loading new modules, or dropping modules which are no
2303 longer indirectly required by the target.</para>
2309 <literal>:set</literal> <optional><replaceable>option</replaceable>...</optional>
2310 <indexterm><primary><literal>:set</literal></primary></indexterm>
2313 <para>Sets various options. See <xref linkend="ghci-set"/> for a list of
2314 available options and <xref linkend="interactive-mode-options"/> for a
2315 list of GHCi-specific flags. The <literal>:set</literal> command by
2316 itself shows which options are currently set. It also lists the current
2317 dynamic flag settings, with GHCi-specific flags listed separately.</para>
2323 <literal>:set</literal> <literal>args</literal> <replaceable>arg</replaceable> ...
2324 <indexterm><primary><literal>:set args</literal></primary></indexterm>
2327 <para>Sets the list of arguments which are returned when the
2328 program calls <literal>System.getArgs</literal><indexterm><primary>getArgs</primary>
2329 </indexterm>.</para>
2335 <literal>:set</literal> <literal>editor</literal> <replaceable>cmd</replaceable>
2338 <para>Sets the command used by <literal>:edit</literal> to
2339 <replaceable>cmd</replaceable>.</para>
2345 <literal>:set</literal> <literal>prog</literal> <replaceable>prog</replaceable>
2346 <indexterm><primary><literal>:set prog</literal></primary></indexterm>
2349 <para>Sets the string to be returned when the program calls
2350 <literal>System.getProgName</literal><indexterm><primary>getProgName</primary>
2351 </indexterm>.</para>
2357 <literal>:set</literal> <literal>prompt</literal> <replaceable>prompt</replaceable>
2360 <para>Sets the string to be used as the prompt in GHCi.
2361 Inside <replaceable>prompt</replaceable>, the sequence
2362 <literal>%s</literal> is replaced by the names of the
2363 modules currently in scope, and <literal>%%</literal> is
2364 replaced by <literal>%</literal>.</para>
2370 <literal>:set</literal> <literal>stop</literal>
2371 [<replaceable>num</replaceable>] <replaceable>cmd</replaceable>
2374 <para>Set a command to be executed when a breakpoint is hit, or a new
2375 item in the history is selected. The most common use of
2376 <literal>:set stop</literal> is to display the source code at the
2377 current location, e.g. <literal>:set stop :list</literal>.</para>
2379 <para>If a number is given before the command, then the commands are
2380 run when the specified breakpoint (only) is hit. This can be quite
2381 useful: for example, <literal>:set stop 1 :continue</literal>
2382 effectively disables breakpoint 1, by running
2383 <literal>:continue</literal> whenever it is hit (although GHCi will
2384 still emit a message to say the breakpoint was hit). What's more,
2385 with cunning use of <literal>:def</literal> and
2386 <literal>:cmd</literal> you can use <literal>:set stop</literal> to
2387 implement conditional breakpoints:</para>
2389 *Main> :def cond \expr -> return (":cmd if (" ++ expr ++ ") then return \"\" else return \":continue\"")
2390 *Main> :set stop 0 :cond (x < 3)
2392 <para>Ignoring breakpoints for a specified number of iterations is
2393 also possible using similar techniques.</para>
2399 <literal>:show bindings</literal>
2400 <indexterm><primary><literal>:show bindings</literal></primary></indexterm>
2403 <para>Show the bindings made at the prompt and their
2410 <literal>:show breaks</literal>
2411 <indexterm><primary><literal>:show breaks</literal></primary></indexterm>
2414 <para>List the active breakpoints.</para>
2420 <literal>:show context</literal>
2421 <indexterm><primary><literal>:show context</literal></primary></indexterm>
2424 <para>List the active evaluations that are stopped at breakpoints.</para>
2430 <literal>:show modules</literal>
2431 <indexterm><primary><literal>:show modules</literal></primary></indexterm>
2434 <para>Show the list of modules currently loaded.</para>
2440 <literal>:show packages</literal>
2441 <indexterm><primary><literal>:show packages</literal></primary></indexterm>
2444 <para>Show the currently active package flags, as well as the list of
2445 packages currently loaded.</para>
2451 <literal>:show languages</literal>
2452 <indexterm><primary><literal>:show languages</literal></primary></indexterm>
2455 <para>Show the currently active language flags.</para>
2462 <literal>:show [args|prog|prompt|editor|stop]</literal>
2463 <indexterm><primary><literal>:show</literal></primary></indexterm>
2466 <para>Displays the specified setting (see
2467 <literal>:set</literal>).</para>
2473 <literal>:sprint</literal>
2474 <indexterm><primary><literal>:sprint</literal></primary></indexterm>
2477 <para>Prints a value without forcing its evaluation.
2478 <literal>:sprint</literal> is similar to <literal>:print</literal>,
2479 with the difference that unevaluated subterms are not bound to new
2480 variables, they are simply denoted by ‘_’.</para>
2486 <literal>:step [<replaceable>expr</replaceable>]</literal>
2487 <indexterm><primary><literal>:step</literal></primary></indexterm>
2490 <para>Single-step from the last breakpoint. With an expression
2491 argument, begins evaluation of the expression with a
2498 <literal>:trace [<replaceable>expr</replaceable>]</literal>
2499 <indexterm><primary><literal>:trace</literal></primary></indexterm>
2502 <para>Evaluates the given expression (or from the last breakpoint if
2503 no expression is given), and additionally logs the evaluation
2504 steps for later inspection using <literal>:history</literal>. See
2505 <xref linkend="tracing" />.</para>
2511 <literal>:type</literal> <replaceable>expression</replaceable>
2512 <indexterm><primary><literal>:type</literal></primary></indexterm>
2515 <para>Infers and prints the type of
2516 <replaceable>expression</replaceable>, including explicit
2517 forall quantifiers for polymorphic types. The monomorphism
2518 restriction is <emphasis>not</emphasis> applied to the
2519 expression during type inference.</para>
2525 <literal>:undef</literal> <replaceable>name</replaceable>
2526 <indexterm><primary><literal>:undef</literal></primary></indexterm>
2529 <para>Undefines the user-defined command
2530 <replaceable>name</replaceable> (see <literal>:def</literal>
2537 <literal>:unset</literal> <replaceable>option</replaceable>...
2538 <indexterm><primary><literal>:unset</literal></primary></indexterm>
2541 <para>Unsets certain options. See <xref linkend="ghci-set"/>
2542 for a list of available options.</para>
2548 <literal>:!</literal> <replaceable>command</replaceable>...
2549 <indexterm><primary><literal>:!</literal></primary></indexterm>
2550 <indexterm><primary>shell commands</primary><secondary>in GHCi</secondary></indexterm>
2553 <para>Executes the shell command
2554 <replaceable>command</replaceable>.</para>
2561 <sect1 id="ghci-set">
2562 <title>The <literal>:set</literal> command</title>
2563 <indexterm><primary><literal>:set</literal></primary></indexterm>
2565 <para>The <literal>:set</literal> command sets two types of
2566 options: GHCi options, which begin with
2567 ‘<literal>+</literal>’, and “command-line”
2568 options, which begin with ‘-’. </para>
2570 <para>NOTE: at the moment, the <literal>:set</literal> command
2571 doesn't support any kind of quoting in its arguments: quotes will
2572 not be removed and cannot be used to group words together. For
2573 example, <literal>:set -DFOO='BAR BAZ'</literal> will not do what
2577 <title>GHCi options</title>
2578 <indexterm><primary>options</primary><secondary>GHCi</secondary>
2581 <para>GHCi options may be set using <literal>:set</literal> and
2582 unset using <literal>:unset</literal>.</para>
2584 <para>The available GHCi options are:</para>
2589 <literal>+r</literal>
2590 <indexterm><primary><literal>+r</literal></primary></indexterm>
2591 <indexterm><primary>CAFs</primary><secondary>in GHCi</secondary></indexterm>
2592 <indexterm><primary>Constant Applicative Form</primary><see>CAFs</see></indexterm>
2595 <para>Normally, any evaluation of top-level expressions
2596 (otherwise known as CAFs or Constant Applicative Forms) in
2597 loaded modules is retained between evaluations. Turning
2598 on <literal>+r</literal> causes all evaluation of
2599 top-level expressions to be discarded after each
2600 evaluation (they are still retained
2601 <emphasis>during</emphasis> a single evaluation).</para>
2603 <para>This option may help if the evaluated top-level
2604 expressions are consuming large amounts of space, or if
2605 you need repeatable performance measurements.</para>
2611 <literal>+s</literal>
2612 <indexterm><primary><literal>+s</literal></primary></indexterm>
2615 <para>Display some stats after evaluating each expression,
2616 including the elapsed time and number of bytes allocated.
2617 NOTE: the allocation figure is only accurate to the size
2618 of the storage manager's allocation area, because it is
2619 calculated at every GC. Hence, you might see values of
2620 zero if no GC has occurred.</para>
2626 <literal>+t</literal>
2627 <indexterm><primary><literal>+t</literal></primary></indexterm>
2630 <para>Display the type of each variable bound after a
2631 statement is entered at the prompt. If the statement is a
2632 single expression, then the only variable binding will be
2634 ‘<literal>it</literal>’.</para>
2640 <sect2 id="ghci-cmd-line-options">
2641 <title>Setting GHC command-line options in GHCi</title>
2643 <para>Normal GHC command-line options may also be set using
2644 <literal>:set</literal>. For example, to turn on
2645 <option>-fglasgow-exts</option>, you would say:</para>
2648 Prelude> :set -fglasgow-exts
2651 <para>Any GHC command-line option that is designated as
2652 <firstterm>dynamic</firstterm> (see the table in <xref
2653 linkend="flag-reference"/>), may be set using
2654 <literal>:set</literal>. To unset an option, you can set the
2655 reverse option:</para>
2656 <indexterm><primary>dynamic</primary><secondary>options</secondary></indexterm>
2659 Prelude> :set -fno-glasgow-exts
2662 <para><xref linkend="flag-reference"/> lists the reverse for each
2663 option where applicable.</para>
2665 <para>Certain static options (<option>-package</option>,
2666 <option>-I</option>, <option>-i</option>, and
2667 <option>-l</option> in particular) will also work, but some may
2668 not take effect until the next reload.</para>
2669 <indexterm><primary>static</primary><secondary>options</secondary></indexterm>
2672 <sect1 id="ghci-dot-files">
2673 <title>The <filename>.ghci</filename> file</title>
2674 <indexterm><primary><filename>.ghci</filename></primary><secondary>file</secondary>
2676 <indexterm><primary>startup</primary><secondary>files, GHCi</secondary>
2679 <para>When it starts, unless the <literal>-ignore-dot-ghci</literal>
2680 flag is given, GHCi reads and executes commands from the following
2681 files, in this order, if they exist:</para>
2685 <para><filename>./.ghci</filename></para>
2688 <para><literal><replaceable>appdata</replaceable>/ghc/ghci.conf</literal>,
2689 where <replaceable>appdata</replaceable> depends on your system,
2690 but is usually something like <literal>C:/Documents and Settings/<replaceable>user</replaceable>/Application Data</literal></para>
2693 <para>On Unix: <literal>$HOME/.ghc/ghci.conf</literal></para>
2696 <para><literal>$HOME/.ghci</literal></para>
2700 <para>The <filename>ghci.conf</filename> file is most useful for
2701 turning on favourite options (eg. <literal>:set +s</literal>), and
2702 defining useful macros. Placing a <filename>.ghci</filename> file
2703 in a directory with a Haskell project is a useful way to set
2704 certain project-wide options so you don't have to type them
2705 everytime you start GHCi: eg. if your project uses GHC extensions
2706 and CPP, and has source files in three subdirectories A, B and C,
2707 you might put the following lines in
2708 <filename>.ghci</filename>:</para>
2711 :set -fglasgow-exts -cpp
2715 <para>(Note that strictly speaking the <option>-i</option> flag is
2716 a static one, but in fact it works to set it using
2717 <literal>:set</literal> like this. The changes won't take effect
2718 until the next <literal>:load</literal>, though.)</para>
2720 <para>Once you have a library of GHCi macros, you may want
2721 to source them from separate files, or you may want to source
2722 your <filename>.ghci</filename> file into your running GHCi
2723 session while debugging it</para>
2726 :def source readFile
2729 <para>With this macro defined in your <filename>.ghci</filename>
2730 file, you can use <literal>:source file</literal> to read GHCi
2731 commands from <literal>file</literal>. You can find (and contribute!-)
2732 other suggestions for <filename>.ghci</filename> files on this Haskell
2734 url="http://haskell.org/haskellwiki/GHC/GHCi">GHC/GHCi</ulink></para>
2736 <para>Two command-line options control whether the
2737 startup files files are read:</para>
2742 <option>-ignore-dot-ghci</option>
2743 <indexterm><primary><option>-ignore-dot-ghci</option></primary></indexterm>
2746 <para>Don't read either <filename>./.ghci</filename> or the
2747 other startup files when starting up.</para>
2752 <option>-read-dot-ghci</option>
2753 <indexterm><primary><option>-read-dot-ghci</option></primary></indexterm>
2756 <para>Read <filename>./.ghci</filename> and the other
2757 startup files (see above). This is normally the
2758 default, but the <option>-read-dot-ghci</option> option may
2759 be used to override a previous
2760 <option>-ignore-dot-ghci</option> option.</para>
2767 <sect1 id="ghci-obj">
2768 <title>Compiling to object code inside GHCi</title>
2770 <para>By default, GHCi compiles Haskell source code into byte-code
2771 that is interpreted by the runtime system. GHCi can also compile
2772 Haskell code to object code: to turn on this feature, use the
2773 <option>-fobject-code</option> flag either on the command line or
2774 with <literal>:set</literal> (the option
2775 <option>-fbyte-code</option> restores byte-code compilation
2776 again). Compiling to object code takes longer, but typically the
2777 code will execute 10-20 times faster than byte-code.</para>
2779 <para>Compiling to object code inside GHCi is particularly useful
2780 if you are developing a compiled application, because the
2781 <literal>:reload</literal> command typically runs much faster than
2782 restarting GHC with <option>--make</option> from the command-line,
2783 because all the interface files are already cached in
2786 <para>There are disadvantages to compiling to object-code: you
2787 can't set breakpoints in object-code modules, for example. Only
2788 the exports of an object-code module will be visible in GHCi,
2789 rather than all top-level bindings as in interpreted
2793 <sect1 id="ghci-faq">
2794 <title>FAQ and Things To Watch Out For</title>
2798 <term>The interpreter can't load modules with foreign export
2799 declarations!</term>
2801 <para>Unfortunately not. We haven't implemented it yet.
2802 Please compile any offending modules by hand before loading
2803 them into GHCi.</para>
2809 <literal>-O</literal> doesn't work with GHCi!
2810 <indexterm><primary><option>-O</option></primary></indexterm>
2813 <para>For technical reasons, the bytecode compiler doesn't
2814 interact well with one of the optimisation passes, so we
2815 have disabled optimisation when using the interpreter. This
2816 isn't a great loss: you'll get a much bigger win by
2817 compiling the bits of your code that need to go fast, rather
2818 than interpreting them with optimisation turned on.</para>
2823 <term>Unboxed tuples don't work with GHCi</term>
2825 <para>That's right. You can always compile a module that
2826 uses unboxed tuples and load it into GHCi, however.
2827 (Incidentally the previous point, namely that
2828 <literal>-O</literal> is incompatible with GHCi, is because
2829 the bytecode compiler can't deal with unboxed
2835 <term>Concurrent threads don't carry on running when GHCi is
2836 waiting for input.</term>
2838 <para>This should work, as long as your GHCi was built with
2839 the <option>-threaded</option> switch, which is the default.
2840 Consult whoever supplied your GHCi installation.</para>
2845 <term>After using <literal>getContents</literal>, I can't use
2846 <literal>stdin</literal> again until I do
2847 <literal>:load</literal> or <literal>:reload</literal>.</term>
2850 <para>This is the defined behaviour of
2851 <literal>getContents</literal>: it puts the stdin Handle in
2852 a state known as <firstterm>semi-closed</firstterm>, wherein
2853 any further I/O operations on it are forbidden. Because I/O
2854 state is retained between computations, the semi-closed
2855 state persists until the next <literal>:load</literal> or
2856 <literal>:reload</literal> command.</para>
2858 <para>You can make <literal>stdin</literal> reset itself
2859 after every evaluation by giving GHCi the command
2860 <literal>:set +r</literal>. This works because
2861 <literal>stdin</literal> is just a top-level expression that
2862 can be reverted to its unevaluated state in the same way as
2863 any other top-level expression (CAF).</para>
2868 <term>I can't use Control-C to interrupt computations in
2869 GHCi on Windows.</term>
2871 <para>See <xref linkend="ghci-windows"/>.</para>
2876 <term>The default buffering mode is different in GHCi to GHC.</term>
2879 In GHC, the stdout handle is line-buffered by default.
2880 However, in GHCi we turn off the buffering on stdout,
2881 because this is normally what you want in an interpreter:
2882 output appears as it is generated.
2892 ;;; Local Variables: ***
2894 ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") ***