ghci.xml 126 KB
Newer Older
1
<?xml version="1.0" encoding="iso-8859-1"?>
2
<chapter id="ghci">
3
  <title>Using GHCi</title>
4
  <indexterm><primary>GHCi</primary></indexterm>
5 6
  <indexterm><primary>interpreter</primary><see>GHCi</see></indexterm>
  <indexterm><primary>interactive</primary><see>GHCi</see></indexterm>
daniel.is.fischer's avatar
daniel.is.fischer committed
7

8 9 10 11 12
  <para>GHCi<footnote>
      <para>The &lsquo;i&rsquo; stands for &ldquo;Interactive&rdquo;</para>
    </footnote>
  is GHC's interactive environment, in which Haskell expressions can
  be interactively evaluated and programs can be interpreted.  If
ross's avatar
ross committed
13
  you're familiar with <ulink url="http://www.haskell.org/hugs/">Hugs</ulink><indexterm><primary>Hugs</primary>
14 15
  </indexterm>, then you'll be right at home with GHCi.  However, GHCi
  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>
Simon Marlow's avatar
Simon Marlow committed
17
  </footnote> the language extensions that GHC provides.
18
  <indexterm><primary>FFI</primary><secondary>GHCi support</secondary></indexterm>
Simon Marlow's avatar
Simon Marlow committed
19 20
  <indexterm><primary>Foreign Function
  Interface</primary><secondary>GHCi support</secondary></indexterm>.
Ian Lynagh's avatar
Ian Lynagh committed
21
  GHCi also includes an interactive debugger (see <xref linkend="ghci-debugger"/>).</para>
22

23
  <sect1 id="ghci-introduction">
24 25 26 27 28 29 30
    <title>Introduction to GHCi</title>

    <para>Let's start with an example GHCi session.  You can fire up
    GHCi with the command <literal>ghci</literal>:</para>

<screen>
$ ghci
31 32 33
GHCi, version 6.12.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
34
Loading package base ... linking ... done.
35
Loading package ffi-1.0 ... linking ... done.
daniel.is.fischer's avatar
daniel.is.fischer committed
36
Prelude>
37 38 39
</screen>

    <para>There may be a short pause while GHCi loads the prelude and
40
    standard libraries, after which the prompt is shown. As the banner
41 42 43 44 45
    says, you can type <literal>:?</literal> to see the list of
    commands available, and a half line description of each of them.
    We'll explain most of these commands as we go along, and there is
    complete documentation for all the commands in
      <xref linkend="ghci-commands" />.</para>
46 47 48 49 50 51 52 53

    <para>Haskell expressions can be typed at the prompt:</para>
    <indexterm><primary>prompt</primary><secondary>GHCi</secondary>
  </indexterm>

<screen>
Prelude> 1+2
3
54
Prelude> let x = 42 in x / 9
55
4.666666666666667
daniel.is.fischer's avatar
daniel.is.fischer committed
56
Prelude>
57 58 59
</screen>

    <para>GHCi interprets the whole line as an expression to evaluate.
daniel.is.fischer's avatar
daniel.is.fischer committed
60
    The expression may not span several lines - as soon as you press enter,
vivian's avatar
vivian committed
61 62 63
    GHCi will attempt to evaluate it.</para>

    <para>In Haskell, a <literal>let</literal> expression is followed
daniel.is.fischer's avatar
daniel.is.fischer committed
64 65 66 67
    by <literal>in</literal>.  However, in GHCi, since the expression
    can also be interpreted in the <literal>IO</literal> monad,
    a <literal>let</literal> binding with no accompanying
    <literal>in</literal> statement can be signalled by an empty line,
vivian's avatar
vivian committed
68
    as in the above example.</para>
69 70
  </sect1>

71
  <sect1 id="loading-source-files">
72 73 74
    <title>Loading source files</title>

    <para>Suppose we have the following Haskell source code, which we
75
    place in a file <filename>Main.hs</filename>:</para>
76 77 78 79 80 81 82 83

<programlisting>
main = print (fac 20)

fac 0 = 1
fac n = n * fac (n-1)
</programlisting>

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    <para>You can save <filename>Main.hs</filename> anywhere you like,
    but if you save it somewhere other than the current
    directory<footnote><para>If you started up GHCi from the command
    line then GHCi's current directory is the same as the current
    directory of the shell from which it was started.  If you started
    GHCi from the &ldquo;Start&rdquo; menu in Windows, then the
    current directory is probably something like
    <filename>C:\Documents and Settings\<replaceable>user
    name</replaceable></filename>.</para> </footnote> then we will
    need to change to the right directory in GHCi:</para>

<screen>
Prelude> :cd <replaceable>dir</replaceable>
</screen>

    <para>where <replaceable>dir</replaceable> is the directory (or
    folder) in which you saved <filename>Main.hs</filename>.</para>

102 103
    <para>To load a Haskell source file into GHCi, use the
    <literal>:load</literal> command:</para>
104
    <indexterm><primary><literal>:load</literal></primary></indexterm>
105 106 107 108 109

<screen>
Prelude> :load Main
Compiling Main             ( Main.hs, interpreted )
Ok, modules loaded: Main.
110
*Main>
111 112 113
</screen>

    <para>GHCi has loaded the <literal>Main</literal> module, and the
114
    prompt has changed to &ldquo;<literal>*Main></literal>&rdquo; to
115
    indicate that the current context for expressions typed at the
116 117
    prompt is the <literal>Main</literal> module we just loaded (we'll
    explain what the <literal>*</literal> means later in <xref
118
    linkend="ghci-scope"/>).  So we can now type expressions involving
119
    the functions from <filename>Main.hs</filename>:</para>
120 121

<screen>
122
*Main> fac 17
123 124 125 126 127 128 129 130 131 132 133 134
355687428096000
</screen>

    <para>Loading a multi-module program is just as straightforward;
    just give the name of the &ldquo;topmost&rdquo; module to the
    <literal>:load</literal> command (hint: <literal>:load</literal>
    can be abbreviated to <literal>:l</literal>).  The topmost module
    will normally be <literal>Main</literal>, but it doesn't have to
    be.  GHCi will discover which modules are required, directly or
    indirectly, by the topmost module, and load them all in dependency
    order.</para>

135
    <sect2 id="ghci-modules-filenames">
136
      <title>Modules vs. filenames</title>
137 138
      <indexterm><primary>modules</primary><secondary>and filenames</secondary></indexterm>
      <indexterm><primary>filenames</primary><secondary>of modules</secondary></indexterm>
daniel.is.fischer's avatar
daniel.is.fischer committed
139

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
      <para>Question: How does GHC find the filename which contains
      module <replaceable>M</replaceable>?  Answer: it looks for the
      file <literal><replaceable>M</replaceable>.hs</literal>, or
      <literal><replaceable>M</replaceable>.lhs</literal>.  This means
      that for most modules, the module name must match the filename.
      If it doesn't, GHCi won't be able to find it.</para>

      <para>There is one exception to this general rule: when you load
      a program with <literal>:load</literal>, or specify it when you
      invoke <literal>ghci</literal>, you can give a filename rather
      than a module name.  This filename is loaded if it exists, and
      it may contain any module you like.  This is particularly
      convenient if you have several <literal>Main</literal> modules
      in the same directory and you can't call them all
      <filename>Main.hs</filename>.</para>

156 157 158 159 160 161 162
      <para>The search path for finding source files is specified with
      the <option>-i</option> option on the GHCi command line, like
      so:</para>
<screen>ghci -i<replaceable>dir<subscript>1</subscript></replaceable>:...:<replaceable>dir<subscript>n</subscript></replaceable></screen>

      <para>or it can be set using the <literal>:set</literal> command
      from within GHCi (see <xref
163
      linkend="ghci-cmd-line-options"/>)<footnote><para>Note that in
164
      GHCi, and <option>&ndash;&ndash;make</option> mode, the <option>-i</option>
165 166 167 168
      option is used to specify the search path for
      <emphasis>source</emphasis> files, whereas in standard
      batch-compilation mode the <option>-i</option> option is used to
      specify the search path for interface files, see <xref
169
      linkend="search-path"/>.</para> </footnote></para>
170

171 172 173 174 175 176 177 178 179
      <para>One consequence of the way that GHCi follows dependencies
      to find modules to load is that every module must have a source
      file.  The only exception to the rule is modules that come from
      a package, including the <literal>Prelude</literal> and standard
      libraries such as <literal>IO</literal> and
      <literal>Complex</literal>.  If you attempt to load a module for
      which GHCi can't find a source file, even if there are object
      and interface files for the module, you'll get an error
      message.</para>
180 181 182 183
    </sect2>

    <sect2>
      <title>Making changes and recompilation</title>
184
      <indexterm><primary><literal>:reload</literal></primary></indexterm>
185 186 187 188 189 190 191

      <para>If you make some changes to the source code and want GHCi
      to recompile the program, give the <literal>:reload</literal>
      command.  The program will be recompiled as necessary, with GHCi
      doing its best to avoid actually recompiling modules if their
      external dependencies haven't changed.  This is the same
      mechanism we use to avoid re-compiling modules in the batch
192
      compilation setting (see <xref linkend="recomp"/>).</para>
193 194 195 196 197
    </sect2>
  </sect1>

  <sect1 id="ghci-compiled">
    <title>Loading compiled code</title>
198
    <indexterm><primary>compiled code</primary><secondary>in GHCi</secondary></indexterm>
199 200 201 202 203

    <para>When you load a Haskell source module into GHCi, it is
    normally converted to byte-code and run using the interpreter.
    However, interpreted code can also run alongside compiled code in
    GHCi; indeed, normally when GHCi starts, it loads up a compiled
204 205
    copy of the <literal>base</literal> package, which contains the
    <literal>Prelude</literal>.</para>
206 207 208 209 210 211 212 213

    <para>Why should we want to run compiled code?  Well, compiled
    code is roughly 10x faster than interpreted code, but takes about
    2x longer to produce (perhaps longer if optimisation is on).  So
    it pays to compile the parts of a program that aren't changing
    very often, and use the interpreter for the code being actively
    developed.</para>

214 215 216 217 218 219
    <para>When loading up source modules with <literal>:load</literal>,
    GHCi normally looks for any corresponding compiled object files,
    and will use one in preference to interpreting the source if
    possible.  For example, suppose we have a 4-module program
    consisting of modules A, B, C, and D.  Modules B and C both import
    D only, and A imports both B &amp; C:</para>
220 221 222 223 224 225 226 227 228 229 230 231
<screen>
      A
     / \
    B   C
     \ /
      D
</screen>
    <para>We can compile D, then load the whole program, like this:</para>
<screen>
Prelude> :! ghc -c D.hs
Prelude> :load A
Compiling B                ( B.hs, interpreted )
232
Compiling C                ( C.hs, interpreted )
233 234
Compiling A                ( A.hs, interpreted )
Ok, modules loaded: A, B, C, D.
235
*Main>
236 237
</screen>

238 239 240 241
    <para>In the messages from the compiler, we see that there is no line
    for <literal>D</literal>. This is because
    it isn't necessary to compile <literal>D</literal>,
    because the source and everything it depends on
242 243
    is unchanged since the last compilation.</para>

daniel.is.fischer's avatar
daniel.is.fischer committed
244
    <para>At any time you can use the command
245 246 247 248 249 250 251 252 253 254 255 256
    <literal>:show modules</literal>
    to get a list of the modules currently loaded
    into GHCi:</para>

<screen>
*Main> :show modules
D                ( D.hs, D.o )
C                ( C.hs, interpreted )
B                ( B.hs, interpreted )
A                ( A.hs, interpreted )
*Main></screen>

257
    <para>If we now modify the source of D (or pretend to: using the Unix
258 259 260 261 262
    command <literal>touch</literal> on the source file is handy for
    this), the compiler will no longer be able to use the object file,
    because it might be out of date:</para>

<screen>
263 264
*Main> :! touch D.hs
*Main> :reload
265 266
Compiling D                ( D.hs, interpreted )
Ok, modules loaded: A, B, C, D.
daniel.is.fischer's avatar
daniel.is.fischer committed
267
*Main>
268 269 270 271 272 273 274 275 276 277
</screen>

    <para>Note that module D was compiled, but in this instance
    because its source hadn't really changed, its interface remained
    the same, and the recompilation checker determined that A, B and C
    didn't need to be recompiled.</para>

    <para>So let's try compiling one of the other modules:</para>

<screen>
278 279
*Main> :! ghc -c C.hs
*Main> :load A
280 281
Compiling D                ( D.hs, interpreted )
Compiling B                ( B.hs, interpreted )
282
Compiling C                ( C.hs, interpreted )
283 284 285 286 287 288 289 290 291 292 293
Compiling A                ( A.hs, interpreted )
Ok, modules loaded: A, B, C, D.
</screen>

    <para>We didn't get the compiled version of C!  What happened?
    Well, in GHCi a compiled module may only depend on other compiled
    modules, and in this case C depends on D, which doesn't have an
    object file, so GHCi also rejected C's object file.  Ok, so let's
    also compile D:</para>

<screen>
294 295
*Main> :! ghc -c D.hs
*Main> :reload
296 297 298 299 300 301 302 303
Ok, modules loaded: A, B, C, D.
</screen>

    <para>Nothing happened!  Here's another lesson: newly compiled
    modules aren't picked up by <literal>:reload</literal>, only
    <literal>:load</literal>:</para>

<screen>
304
*Main> :load A
305 306 307 308 309
Compiling B                ( B.hs, interpreted )
Compiling A                ( A.hs, interpreted )
Ok, modules loaded: A, B, C, D.
</screen>

310 311 312 313
    <para>The automatic loading of object files can sometimes lead to
    confusion, because non-exported top-level definitions of a module
    are only available for use in expressions at the prompt when the
    module is interpreted (see <xref linkend="ghci-scope" />).  For
Simon Marlow's avatar
Simon Marlow committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
    this reason, you might sometimes want to force GHCi to load a
    module using the interpreter.  This can be done by prefixing
      a <literal>*</literal> to the module name or filename when
      using <literal>:load</literal>, for example</para>

<screen>
Prelude> :load *A
Compiling A                ( A.hs, interpreted )
*A>
</screen>

<para>When the <literal>*</literal> is used, GHCi ignores any
  pre-compiled object code and interprets the module.  If you have
  already loaded a number of modules as object code and decide that
  you wanted to interpret one of them, instead of re-loading the whole
  set you can use <literal>:add *M</literal> to specify that you want
  <literal>M</literal> to be interpreted (note that this might cause
  other modules to be interpreted too, because compiled modules cannot
  depend on interpreted ones).</para>

<para>To always compile everything to object code and never use the
  interpreter, use the <literal>-fobject-code</literal> option (see
  <xref linkend="ghci-obj" />).</para>
337

338
    <para>HINT: since GHCi will only use a compiled object file if it
Ian Lynagh's avatar
Ian Lynagh committed
339
    can be sure that the compiled version is up-to-date, a good technique
340
    when working on a large program is to occasionally run
341
    <literal>ghc &ndash;&ndash;make</literal> to compile the whole project (say
342
    before you go for lunch :-), then continue working in the
343
    interpreter.  As you modify code, the changed modules will be
344 345 346 347
    interpreted, but the rest of the project will remain
    compiled.</para>
  </sect1>

348
  <sect1 id="interactive-evaluation">
349 350 351
    <title>Interactive evaluation at the prompt</title>

    <para>When you type an expression at the prompt, GHCi immediately
352 353 354 355 356 357 358 359 360
    evaluates and prints the result:
<screen>
Prelude> reverse "hello"
"olleh"
Prelude> 5+5
10
</screen>
</para>

361
<sect2 id="actions-at-prompt"><title>I/O actions at the prompt</title>
362

363
<para>GHCi does more than simple expression evaluation at the prompt.
364
If you enter an expression of type <literal>IO a</literal> for some
365 366
    <literal>a</literal>, then GHCi <emphasis>executes</emphasis> it
    as an IO-computation.
367 368 369 370 371 372
<screen>
Prelude> "hello"
"hello"
Prelude> putStrLn "hello"
hello
</screen>
373 374 375 376 377 378
This works even if the type of the expression is more general,
provided it can be <emphasis>instantiated</emphasis> to <literal>IO a</literal>.  For example
<screen>
Prelude> return True
True
</screen>
379 380 381 382 383 384 385 386 387 388 389 390 391 392
Furthermore, GHCi will print the result of the I/O action if (and only
if):
<itemizedlist>
  <listitem><para>The result type is an instance of <literal>Show</literal>.</para></listitem>
  <listitem><para>The result type is not
  <literal>()</literal>.</para></listitem>
</itemizedlist>
For example, remembering that <literal>putStrLn :: String -> IO ()</literal>:
<screen>
Prelude> putStrLn "hello"
hello
Prelude> do { putStrLn "hello"; return "yes" }
hello
"yes"
393
</screen>
394
</para></sect2>
395

396
    <sect2 id="ghci-stmts">
397 398 399
      <title>Using <literal>do-</literal>notation at the prompt</title>
      <indexterm><primary>do-notation</primary><secondary>in GHCi</secondary></indexterm>
      <indexterm><primary>statements</primary><secondary>in GHCi</secondary></indexterm>
daniel.is.fischer's avatar
daniel.is.fischer committed
400

401 402 403 404
      <para>GHCi actually accepts <firstterm>statements</firstterm>
      rather than just expressions at the prompt.  This means you can
      bind values and functions to names, and use them in future
      expressions or statements.</para>
405

406 407 408 409 410
      <para>The syntax of a statement accepted at the GHCi prompt is
      exactly the same as the syntax of a statement in a Haskell
      <literal>do</literal> expression.  However, there's no monad
      overloading here: statements typed at the prompt must be in the
      <literal>IO</literal> monad.
411
<screen>
412 413 414 415
Prelude> x &lt;- return 42
Prelude> print x
42
Prelude>
416
</screen>
417 418 419 420 421 422
      The statement <literal>x &lt;- return 42</literal> means
      &ldquo;execute <literal>return 42</literal> in the
      <literal>IO</literal> monad, and bind the result to
      <literal>x</literal>&rdquo;.  We can then use
      <literal>x</literal> in future statements, for example to print
      it as we did above.</para>
423

424
      <para>If <option>-fprint-bind-result</option> is set then
daniel.is.fischer's avatar
daniel.is.fischer committed
425
      GHCi will print the result of a statement if and only if:
426 427
	<itemizedlist>
	  <listitem>
daniel.is.fischer's avatar
daniel.is.fischer committed
428
	    <para>The statement is not a binding, or it is a monadic binding
429 430 431 432 433 434 435 436 437
	      (<literal>p &lt;- e</literal>) that binds exactly one
	      variable.</para>
	  </listitem>
	  <listitem>
	    <para>The variable's type is not polymorphic, is not
	      <literal>()</literal>, and is an instance of
	      <literal>Show</literal></para>
	  </listitem>
	</itemizedlist>
438 439
      <indexterm><primary><option>-fprint-bind-result</option></primary></indexterm><indexterm><primary><option>-fno-print-bind-result</option></primary></indexterm>.
      </para>
440

441 442 443 444
      <para>Of course, you can also bind normal non-IO expressions
      using the <literal>let</literal>-statement:</para>
<screen>
Prelude> let x = 42
445
Prelude> x
446 447 448
42
Prelude>
</screen>
449
      <para>Another important difference between the two types of binding
450 451 452 453 454 455 456 457 458 459
      is that the monadic bind (<literal>p &lt;- e</literal>) is
      <emphasis>strict</emphasis> (it evaluates <literal>e</literal>),
      whereas with the <literal>let</literal> form, the expression
      isn't evaluated immediately:</para>
<screen>
Prelude> let x = error "help!"
Prelude> print x
*** Exception: help!
Prelude>
</screen>
460 461 462 463

      <para>Note that <literal>let</literal> bindings do not automatically
	print the value bound, unlike monadic bindings.</para>

464 465 466 467 468 469 470 471
      <para>Hint: you can also use <literal>let</literal>-statements
      to define functions at the prompt:</para>
<screen>
Prelude> let add a b = a + b
Prelude> add 1 2
3
Prelude>
</screen>
daniel.is.fischer's avatar
daniel.is.fischer committed
472
        <para>However, this quickly gets tedious when defining functions
473
        with multiple clauses, or groups of mutually recursive functions,
daniel.is.fischer's avatar
daniel.is.fischer committed
474
        because the complete definition has to be given on a single line,
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
        using explicit braces and semicolons instead of layout:</para>
<screen>
Prelude> let { f op n [] = n ; f op n (h:t) = h `op` f op n t }
Prelude> f (+) 0 [1..3]
6
Prelude>
</screen>
      <para>To alleviate this issue, GHCi commands can be split over
      multiple lines, by wrapping them in <literal>:{</literal> and
      <literal>:}</literal> (each on a single line of its own):</para>
<screen>
Prelude> :{
Prelude| let { g op n [] = n
Prelude|     ; g op n (h:t) = h `op` g op n t
Prelude|     }
Prelude| :}
Prelude> g (*) 1 [1..3]
6
</screen>
      <para>Such multiline commands can be used with any GHCi command,
      and the lines between <literal>:{</literal> and
daniel.is.fischer's avatar
daniel.is.fischer committed
496
      <literal>:}</literal> are simply merged into a single line for
497
      interpretation. That implies that each such group must form a single
daniel.is.fischer's avatar
daniel.is.fischer committed
498
      valid command when merged, and that no layout rule is used.
499 500 501 502
      The main purpose of multiline commands is not to replace module
      loading but to make definitions in .ghci-files (see <xref
      linkend="ghci-dot-files"/>) more readable and maintainable.</para>

503 504 505 506 507 508
      <para>Any exceptions raised during the evaluation or execution
      of the statement are caught and printed by the GHCi command line
      interface (for more information on exceptions, see the module
      <literal>Control.Exception</literal> in the libraries
      documentation).</para>

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
      <para>Every new binding shadows any existing bindings of the
      same name, including entities that are in scope in the current
      module context.</para>

      <para>WARNING: temporary bindings introduced at the prompt only
      last until the next <literal>:load</literal> or
      <literal>:reload</literal> command, at which time they will be
      simply lost.  However, they do survive a change of context with
      <literal>:module</literal>: the temporary bindings just move to
      the new location.</para>

      <para>HINT: To get a list of the bindings currently in scope, use the
      <literal>:show bindings</literal> command:</para>

<screen>
Prelude> :show bindings
x :: Int
Prelude></screen>

      <para>HINT: if you turn on the <literal>+t</literal> option,
      GHCi will show the type of each variable bound by a statement.
      For example:</para>
      <indexterm><primary><literal>+t</literal></primary></indexterm>
<screen>
Prelude> :set +t
Prelude> let (x:xs) = [1..]
x :: Integer
xs :: [Integer]
</screen>
538

539
    </sect2>
540

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
    <sect2 id="ghci-multiline">
      <title>Multiline input</title>

      <para>Apart from the <literal>:{ ... :}</literal> syntax for
        multi-line input mentioned above, GHCi also has a multiline
        mode, enabled by <literal>:set +m</literal>,
        <indexterm><primary><literal>:set +m</literal></primary></indexterm>
        in which GHCi detects automatically when the current statement
        is unfinished and allows further lines to be added.  A
        multi-line input is terminated with an empty line.  For example:</para>

<screen>
Prelude> :set +m
Prelude> let x = 42
Prelude|
</screen>

       <para>Further bindings can be added to
       this <literal>let</literal> statement, so GHCi indicates that
       the next line continues the previous one by changing the
       prompt.  Note that layout is in effect, so to add more bindings
         to this <literal>let</literal> we have to line them up:</para>

<screen>
Prelude> :set +m
Prelude> let x = 42
Prelude|     y = 3
Prelude| 
Prelude>
</screen>

       <para>Explicit braces and semicolons can be used instead of
         layout, as usual:</para>

<screen>
Prelude> do {
Prelude| putStrLn "hello"
Prelude| ;putStrLn "world"
Prelude| }
hello
world
Prelude>
</screen>

       <para>Note that after the closing brace, GHCi knows that the
         current statement is finished, so no empty line is required.</para>

       <para>Multiline mode is useful when entering monadic
         <literal>do</literal> statements:</para>

<screen>
Control.Monad.State> flip evalStateT 0 $ do
Control.Monad.State| i &lt;- get
Control.Monad.State| lift $ do
Control.Monad.State|   putStrLn "Hello World!"
Control.Monad.State|   print i
Control.Monad.State|
"Hello World!"
0
Control.Monad.State>
</screen>

   <para>During a multiline interaction, the user can interrupt and
   return to the top-level prompt.</para>

<screen>
Prelude> do
Prelude| putStrLn "Hello, World!"
Prelude| ^C
Prelude>
</screen>
    </sect2>

    <sect2 id="ghci-decls">
      <title>Type, class and other declarations</title>

617
      <para>At the GHCi
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
      prompt you can also enter any top-level Haskell declaration,
      including <literal>data</literal>, <literal>type</literal>, <literal>newtype</literal>, <literal>class</literal>, <literal>instance</literal>, <literal>deriving</literal>,
      and <literal>foreign</literal> declarations.  For
      example:</para>

<screen>
Prelude> data T = A | B | C deriving (Eq, Ord, Show, Enum)
Prelude> [A ..]
[A,B,C]
Prelude> :i T
data T = A | B | C      -- Defined at &lt;interactive>:2:6
instance Enum T -- Defined at &lt;interactive>:2:45
instance Eq T -- Defined at &lt;interactive>:2:30
instance Ord T -- Defined at &lt;interactive>:2:34
instance Show T -- Defined at &lt;interactive>:2:39
</screen>

    <para>As with ordinary variable bindings, later definitions shadow
    earlier ones, so you can re-enter a declaration to fix a problem
    with it or extend it.  But there's a gotcha: when a new type
    declaration shadows an older one, there might be other
    declarations that refer to the old type.  The thing to remember is
    that the old type still exists, and these other declarations still
    refer to the old type.  However, while the old and the new type
    have the same name, GHCi will treat them as distinct.  For
    example:</para>

<screen>
Prelude> data T = A | B
Prelude> let f A = True; f B = False
Prelude> data T = A | B | C
Prelude> f A

&lt;interactive>:2:3:
    Couldn't match expected type `main::Interactive.T'
                with actual type `T'
    In the first argument of `f', namely `A'
    In the expression: f A
    In an equation for `it': it = f A
Prelude> 
</screen>

    <para>The old, shadowed, version of <literal>T</literal> is
      displayed as <literal>main::Interactive.T</literal> by GHCi in
      an attempt to distinguish it from the new <literal>T</literal>,
      which is displayed as simply <literal>T</literal>.</para>

665 666 667 668
    <para>Class and type-family instance declarations are simply added to the list of available isntances, with one
    exception. Since type-family instances are not permitted to overlap, but you might want to re-define one,
    a type-family instance <emphasis>replaces</emphasis> any earlier type instance with an identical left hand side.
    (See <xref linkend="type-families"/>.)</para>
669 670
    </sect2>

671
    <sect2 id="ghci-scope">
daniel.is.fischer's avatar
daniel.is.fischer committed
672
      <title>What's really in scope at the prompt?</title>
673

674 675 676 677 678
      <para>When you type an expression at the prompt, what
      identifiers and types are in scope?  GHCi provides a flexible
      way to control exactly how the context for an expression is
      constructed.  Let's start with the simple cases; when you start
      GHCi the prompt looks like this:</para>
679

680
<screen>Prelude></screen>
681

682
      <para>Which indicates that everything from the module
683 684 685 686 687 688
      <literal>Prelude</literal> is currently in scope; the visible
      identifiers are exactly those that would be visible in a Haskell
      source file with no <literal>import</literal>
      declarations.</para>

      <para>If we now load a file into GHCi, the prompt will change:</para>
689

690 691 692 693 694
<screen>
Prelude> :load Main.hs
Compiling Main             ( Main.hs, interpreted )
*Main>
</screen>
695

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
      <para>The new prompt is <literal>*Main</literal>, which
      indicates that we are typing expressions in the context of the
      top-level of the <literal>Main</literal> module.  Everything
      that is in scope at the top-level in the module
      <literal>Main</literal> we just loaded is also in scope at the
      prompt (probably including <literal>Prelude</literal>, as long
      as <literal>Main</literal> doesn't explicitly hide it).</para>

      <para>The syntax
      <literal>*<replaceable>module</replaceable></literal> indicates
      that it is the full top-level scope of
      <replaceable>module</replaceable> that is contributing to the
      scope for expressions typed at the prompt.  Without the
      <literal>*</literal>, just the exports of the module are
      visible.</para>

      <para>We're not limited to a single module: GHCi can combine
      scopes from multiple modules, in any mixture of
      <literal>*</literal> and non-<literal>*</literal> forms.  GHCi
      combines the scopes from all of these modules to form the scope
716 717 718 719 720
      that is in effect at the prompt.</para>

      <para>NOTE: for technical reasons, GHCi can only support the
      <literal>*</literal>-form for modules that are interpreted.
      Compiled modules and package modules can only contribute their
Simon Marlow's avatar
Simon Marlow committed
721 722 723
      exports to the current scope.  To ensure that GHCi loads the
      interpreted version of a module, add the <literal>*</literal>
      when loading the module, e.g. <literal>:load *M</literal>.</para>
724

725 726
      <para>To add modules to the scope, use ordinary Haskell
      <literal>import</literal> syntax:</para>
727

728
<screen>
729 730
Prelude> import System.IO
Prelude System.IO> hPutStrLn stdout "hello\n"
731
hello
732
Prelude System.IO>
733 734
</screen>

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
      <para>The full Haskell import syntax is supported, including
      <literal>hiding</literal> and <literal>as</literal> clauses.
      The prompt shows the modules that are currently imported, but it
      omits details about <literal>hiding</literal>,
      <literal>as</literal>, and so on.  To see the full story, use
      <literal>:show imports</literal>:</para>

<screen>
Prelude> import System.IO
Prelude System.IO> import Data.Map as Map
Prelude System.IO Map> :show imports
import Prelude -- implicit
import System.IO
import Data.Map as Map
Prelude System.IO Map>
</screen>

      <para>Note that the <literal>Prelude</literal> import is marked
      as implicit.  It can be overriden with an explicit
      <literal>Prelude</literal> import, just like in a Haskell
      module.</para>

      <para>Another way to manipulate the scope is to use the
      <literal>:module</literal> command, which provides a way to do
      two things that cannot be done with ordinary
      <literal>import</literal> declarations:
      <itemizedlist>
        <listitem>
          <para><literal>:module</literal> supports the
          <literal>*</literal> modifier on modules, which opens the
          full top-level scope of a module, rather than just its
          exports.</para>
        </listitem>
        <listitem>
          <para>Imports can be <emphasis>removed</emphasis> from the
          context, using the syntax <literal>:module -M</literal>.
          The <literal>import</literal> syntax is cumulative (as in a
          Haskell module), so this is the only way to subtract from
          the scope.</para>
        </listitem>
      </itemizedlist>
      The full syntax of the <literal>:module</literal> command
      is:</para>
778 779 780 781 782 783 784 785 786 787

<screen>
:module <optional>+|-</optional> <optional>*</optional><replaceable>mod<subscript>1</subscript></replaceable> ... <optional>*</optional><replaceable>mod<subscript>n</subscript></replaceable>
</screen>

      <para>Using the <literal>+</literal> form of the
      <literal>module</literal> commands adds modules to the current
      scope, and <literal>-</literal> removes them.  Without either
      <literal>+</literal> or <literal>-</literal>, the current scope
      is replaced by the set of modules specified.  Note that if you
788 789 790 791 792 793
      use this form and leave out <literal>Prelude</literal>, an
      implicit <literal>Prelude</literal> import will be added
      automatically.</para>

      <para>After a <literal>:load</literal> command, an automatic
      import is added to the scope for the most recently loaded
794 795 796 797 798 799
      "target" module, in a <literal>*</literal>-form if possible.
      For example, if you say <literal>:load foo.hs bar.hs</literal>
      and <filename>bar.hs</filename> contains module
      <literal>Bar</literal>, then the scope will be set to
      <literal>*Bar</literal> if <literal>Bar</literal> is
      interpreted, or if <literal>Bar</literal> is compiled it will be
Ian Lynagh's avatar
Ian Lynagh committed
800
      set to <literal>Prelude Bar</literal> (GHCi automatically adds
801
      <literal>Prelude</literal> if it isn't present and there aren't
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
      any <literal>*</literal>-form modules).  These
      automatically-added imports can be seen with
      <literal>:show imports</literal>:

<screen>
Prelude> :load hello.hs
[1 of 1] Compiling Main             ( hello.hs, interpreted )
Ok, modules loaded: Main.
*Main> :show imports
:module +*Main -- added automatically
*Main>
</screen>

      and the automatically-added import is replaced the next time you
      use <literal>:load</literal>, <literal>:add</literal>, or
      <literal>:reload</literal>.  It can also be removed by
      <literal>:module</literal> as with normal imports.</para>
819 820 821 822 823 824 825 826

      <para>With multiple modules in scope, especially multiple
      <literal>*</literal>-form modules, it is likely that name
      clashes will occur.  Haskell specifies that name clashes are
      only reported when an ambiguous identifier is used, and GHCi
      behaves in the same way for expressions typed at the
      prompt.</para>

Ian Lynagh's avatar
Ian Lynagh committed
827 828 829
      <para>
        Hint: GHCi will tab-complete names that are in scope; for
        example, if you run GHCi and type <literal>J&lt;tab&gt;</literal>
Ian Lynagh's avatar
Ian Lynagh committed
830
        then GHCi will expand it to &ldquo;<literal>Just </literal>&rdquo;.
Ian Lynagh's avatar
Ian Lynagh committed
831 832
      </para>

833 834 835 836 837 838 839 840 841 842 843
      <sect3>
        <title><literal>:module</literal> and
        <literal>:load</literal></title>

        <para>It might seem that <literal>:module</literal> and
        <literal>:load</literal> do similar things: you can use both
        to bring a module into scope.  However, there is a clear
        difference.  GHCi is concerned with two sets of modules:</para>

        <itemizedlist>
          <listitem>
844 845 846 847 848
            <para>The set of modules that are currently
            <emphasis>loaded</emphasis>.  This set is modified by
            <literal>:load</literal>, <literal>:add</literal> and
            <literal>:reload</literal>, and can be shown with
            <literal>:show modules</literal>.
849 850 851 852
            </para>
          </listitem>
          <listitem>
            <para>The set of modules that are currently <emphasis>in
853 854 855 856 857
            scope</emphasis> at the prompt.  This set is modified by
            <literal>import</literal>, <literal>:module</literal>, and
            it is also modified automatically after
            <literal>:load</literal>, <literal>:add</literal>, and
            <literal>:reload</literal>, as described above.</para>
858 859 860 861 862 863 864 865 866 867
          </listitem>
        </itemizedlist>

        <para>You cannot add a module to the scope if it is not
          loaded.  This is why trying to
          use <literal>:module</literal> to load a new module results
          in the message &ldquo;<literal>module M is not
            loaded</literal>&rdquo;.</para>
      </sect3>

868
      <sect3 id="ghci-import-qualified">
869 870 871 872 873
	<title>Qualified names</title>

	<para>To make life slightly easier, the GHCi prompt also
        behaves as if there is an implicit <literal>import
        qualified</literal> declaration for every module in every
874 875
        package, and every module currently loaded into GHCi.  This
          behaviour can be disabled with the flag <option>-fno-implicit-import-qualified</option><indexterm><primary><option>-fno-implicit-import-qualified</option></primary></indexterm>.</para>
876
      </sect3>
Ian Lynagh's avatar
Ian Lynagh committed
877 878

      <sect3>
Ian Lynagh's avatar
Ian Lynagh committed
879
        <title>The <literal>:main</literal> and <literal>:run</literal> commands</title>
Ian Lynagh's avatar
Ian Lynagh committed
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901

        <para>
          When a program is compiled and executed, it can use the
          <literal>getArgs</literal> function to access the
          command-line arguments.
          However, we cannot simply pass the arguments to the
          <literal>main</literal> function while we are testing in ghci,
          as the <literal>main</literal> function doesn't take its
          directly.
        </para>

        <para>
          Instead, we can use the <literal>:main</literal> command.
          This runs whatever <literal>main</literal> is in scope, with
          any arguments being treated the same as command-line arguments,
          e.g.:
        </para>

<screen>
Prelude> let main = System.Environment.getArgs >>= print
Prelude> :main foo bar
["foo","bar"]
Ian Lynagh's avatar
Ian Lynagh committed
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
</screen>

        <para>
            We can also quote arguments which contains characters like
            spaces, and they are treated like Haskell strings, or we can
            just use Haskell list syntax:
        </para>

<screen>
Prelude> :main foo "bar baz"
["foo","bar baz"]
Prelude> :main ["foo", "bar baz"]
["foo","bar baz"]
</screen>

        <para>
            Finally, other functions can be called, either with the
            <literal>-main-is</literal> flag or the <literal>:run</literal>
            command:
        </para>

<screen>
Prelude> let foo = putStrLn "foo" >> System.Environment.getArgs >>= print
Prelude> let bar = putStrLn "bar" >> System.Environment.getArgs >>= print
Prelude> :set -main-is foo
Prelude> :main foo "bar baz"
foo
["foo","bar baz"]
Prelude> :run bar ["foo", "bar baz"]
bar
["foo","bar baz"]
Ian Lynagh's avatar
Ian Lynagh committed
933 934 935
</screen>

      </sect3>
936
    </sect2>
daniel.is.fischer's avatar
daniel.is.fischer committed
937

938 939 940 941 942

    <sect2>
      <title>The <literal>it</literal> variable</title>
      <indexterm><primary><literal>it</literal></primary>
      </indexterm>
daniel.is.fischer's avatar
daniel.is.fischer committed
943

944 945 946 947 948 949 950 951 952
      <para>Whenever an expression (or a non-binding statement, to be
      precise) is typed at the prompt, GHCi implicitly binds its value
      to the variable <literal>it</literal>.  For example:</para>
<screen>
Prelude> 1+2
3
Prelude> it * 2
6
</screen>
953 954 955
    <para>What actually happens is that GHCi typechecks the
    expression, and if it doesn't have an <literal>IO</literal> type,
    then it transforms it as follows: an expression
daniel.is.fischer's avatar
daniel.is.fischer committed
956
    <replaceable>e</replaceable> turns into
Ian Lynagh's avatar
Ian Lynagh committed
957 958 959
<screen>
let it = <replaceable>e</replaceable>;
print it
960
</screen>
961 962 963 964 965 966 967
    which is then run as an IO-action.</para>

    <para>Hence, the original expression must have a type which is an
    instance of the <literal>Show</literal> class, or GHCi will
    complain:</para>

<screen>
Ian Lynagh's avatar
Ian Lynagh committed
968 969 970 971 972 973 974 975
Prelude&gt; id

&lt;interactive&gt;:1:0:
    No instance for (Show (a -&gt; a))
      arising from use of `print' at &lt;interactive&gt;:1:0-1
    Possible fix: add an instance declaration for (Show (a -> a))
    In the expression: print it
    In a 'do' expression: print it
976 977 978 979
</screen>

    <para>The error message contains some clues as to the
    transformation happening internally.</para>
980

981
      <para>If the expression was instead of type <literal>IO a</literal> for
982 983 984 985 986
      some <literal>a</literal>, then <literal>it</literal> will be
      bound to the result of the <literal>IO</literal> computation,
      which is of type <literal>a</literal>.  eg.:</para>
<screen>
Prelude> Time.getClockTime
Ian Lynagh's avatar
Ian Lynagh committed
987
Wed Mar 14 12:23:13 GMT 2001
988 989 990 991
Prelude> print it
Wed Mar 14 12:23:13 GMT 2001
</screen>

992 993
      <para>The corresponding translation for an IO-typed
      <replaceable>e</replaceable> is
Ian Lynagh's avatar
Ian Lynagh committed
994 995
<screen>
it &lt;- <replaceable>e</replaceable>
996 997 998
</screen>
      </para>

999 1000 1001 1002 1003
      <para>Note that <literal>it</literal> is shadowed by the new
      value each time you evaluate a new expression, and the old value
      of <literal>it</literal> is lost.</para>

    </sect2>
1004

1005
    <sect2 id="extended-default-rules">
1006 1007 1008 1009 1010 1011 1012 1013 1014
      <title>Type defaulting in GHCi</title>
    <indexterm><primary>Type default</primary></indexterm>
    <indexterm><primary><literal>Show</literal> class</primary></indexterm>
      <para>
      Consider this GHCi session:
<programlisting>
  ghci> reverse []
</programlisting>
      What should GHCi do?  Strictly speaking, the program is ambiguous.  <literal>show (reverse [])</literal>
Simon Marlow's avatar
Simon Marlow committed
1015
      (which is what GHCi computes here) has type <literal>Show a => String</literal> and how that displays depends
1016 1017
      on the type <literal>a</literal>.  For example:
<programlisting>
Simon Marlow's avatar
Simon Marlow committed
1018
  ghci> reverse ([] :: String)
1019
  ""
Simon Marlow's avatar
Simon Marlow committed
1020
  ghci> reverse ([] :: [Int])
1021 1022 1023
  []
</programlisting>
    However, it is tiresome for the user to have to specify the type, so GHCi extends Haskell's type-defaulting
Simon Marlow's avatar
tweaks  
Simon Marlow committed
1024
    rules (Section 4.3.4 of the Haskell 2010 Report) as follows.  The
1025 1026
    standard rules take each group of constraints <literal>(C1 a, C2 a, ..., Cn
    a)</literal> for each type variable <literal>a</literal>, and defaults the
daniel.is.fischer's avatar
daniel.is.fischer committed
1027
    type variable if
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    <orderedlist>
        <listitem>
            <para>
                The type variable <literal>a</literal> appears in no
                other constraints
            </para>
        </listitem>
        <listitem>
            <para>
                All the classes <literal>Ci</literal> are standard.
            </para>
        </listitem>
        <listitem>
            <para>
                At least one of the classes <literal>Ci</literal> is
                numeric.
            </para>
        </listitem>
    </orderedlist>
    At the GHCi prompt, or with GHC if the
Ian Lynagh's avatar
Ian Lynagh committed
1048
    <literal>-XExtendedDefaultRules</literal> flag is given,
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
    the following additional differences apply:
    <itemizedlist>
        <listitem>
            <para>
                Rule 2 above is relaxed thus:
                <emphasis>All</emphasis> of the classes
                <literal>Ci</literal> are single-parameter type classes.
            </para>
        </listitem>
        <listitem>
            <para>
                Rule 3 above is relaxed this:
                At least one of the classes <literal>Ci</literal> is
                numeric, <emphasis>or is <literal>Show</literal>,
                <literal>Eq</literal>, or
                <literal>Ord</literal></emphasis>.
            </para>
        </listitem>
        <listitem>
            <para>
                The unit type <literal>()</literal> is added to the
                start of the standard list of types which are tried when
                doing type defaulting.
            </para>
        </listitem>
    </itemizedlist>
    The last point means that, for example, this program:
<programlisting>
main :: IO ()
main = print def

instance Num ()

def :: (Num a, Enum a) => a
def = toEnum 0
</programlisting>
    prints <literal>()</literal> rather than <literal>0</literal> as the
    type is defaulted to <literal>()</literal> rather than
    <literal>Integer</literal>.
   </para>
   <para>
    The motivation for the change is that it means <literal>IO a</literal>
    actions default to <literal>IO ()</literal>, which in turn means that
    ghci won't try to print a result when running them. This is
    particularly important for <literal>printf</literal>, which has an
    instance that returns <literal>IO a</literal>.
    However, it is only able to return
    <literal>undefined</literal>
Ian Lynagh's avatar
Ian Lynagh committed
1097 1098
    (the reason for the instance having this type is so that printf
    doesn't require extensions to the class system), so if the type defaults to
1099 1100
    <literal>Integer</literal> then ghci gives an error when running a
    printf.
1101 1102 1103
   </para>
   <para>See also <xref linkend="actions-at-prompt"/> for how the monad of a computational
   expression defaults to <literal>IO</literal> if possible.
1104 1105
   </para>
    </sect2>
1106

1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
   <sect2 id="ghci-interactive-print">
     <title>Using a custom interactive printing function</title>
     <para>[<emphasis role="bold">New in version 7.6.1</emphasis>]
        By default, GHCi prints the result of expressions typed at the prompt
        using the function <literal>System.IO.print</literal>. Its type
        signature is <literal>Show a => a -> IO ()</literal>, and it works by
        converting the value to <literal>String</literal> using
        <literal>show</literal>.
     </para>
     <para>
        This is not ideal in certain cases, like when the output is long, or
        contains strings with non-ascii characters.
     </para>
     <para>
       The <literal>-interactive-print</literal> flag allows to specify any
       function of type <literal>C a => a -> IO ()</literal>, for some
       constraint <literal>C</literal>, as the function for printing evaluated
       expressions. The function can reside in any loaded module or any
       registered package.
     </para>
     <para>
       As an example, suppose we have following special printing module:
       <programlisting>
	 module SpecPrinter where
	 import System.IO

	 sprint a = putStrLn $ show a ++ "!"
       </programlisting>
       The <literal>sprint</literal> function adds an exclamation mark at the
       end of any printed value. Running GHCi with the command:
       <programlisting>
	 ghci -interactive-print=SpecPrinter.sprinter SpecPrinter
       </programlisting>
       will start an interactive session where values with be printed using
       <literal>sprint</literal>:
       <programlisting>
	 *SpecPrinter> [1,2,3]
	 [1,2,3]!
	 *SpecPrinter> 42
	 42!
       </programlisting>
     </para>
     <para>
       A custom pretty printing function can be used, for example, to format
       tree-like and nested structures in a more readable way.
     </para>
     <para>
       The <literal>-interactive-print</literal> flag can also be used when
       running GHC in <literal>-e mode</literal>:
       <programlisting>
	 % ghc -e "[1,2,3]" -interactive-print=SpecPrinter.sprint SpecPrinter
	 [1,2,3]!
       </programlisting>
     </para>
   </sect2>
1162 1163
  </sect1>

Simon Marlow's avatar
Simon Marlow committed
1164 1165 1166 1167 1168 1169 1170 1171
  <sect1 id="ghci-debugger">
    <title>The GHCi Debugger</title>
    <indexterm><primary>debugger</primary><secondary>in GHCi</secondary>
    </indexterm>

    <para>GHCi contains a simple imperative-style debugger in which you can
      stop a running computation in order to examine the values of
      variables.  The debugger is integrated into GHCi, and is turned on by
1172 1173 1174 1175 1176 1177
      default: no flags are required to enable the debugging
      facilities.  There is one major restriction: breakpoints and
      single-stepping are only available in interpreted modules;
      compiled code is invisible to the debugger<footnote><para>Note that packages
      only contain compiled code, so debugging a package requires
      finding its source and loading that directly.</para></footnote>.</para>
Simon Marlow's avatar
Simon Marlow committed
1178 1179 1180 1181

    <para>The debugger provides the following:
    <itemizedlist>
        <listitem>
Ian Lynagh's avatar
Ian Lynagh committed
1182
          <para>The ability to set a <firstterm>breakpoint</firstterm> on a
Simon Marlow's avatar
Simon Marlow committed
1183
            function definition or expression in the program.  When the function
daniel.is.fischer's avatar
daniel.is.fischer committed
1184
            is called, or the expression evaluated, GHCi suspends
Simon Marlow's avatar
Simon Marlow committed
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
            execution and returns to the prompt, where you can inspect the
            values of local variables before continuing with the
            execution.</para>
        </listitem>
        <listitem>
          <para>Execution can be <firstterm>single-stepped</firstterm>: the
            evaluator will suspend execution approximately after every
            reduction, allowing local variables to be inspected.  This is
            equivalent to setting a breakpoint at every point in the
            program.</para>
        </listitem>
        <listitem>
          <para>Execution can take place in <firstterm>tracing
              mode</firstterm>, in which the evaluator remembers each
            evaluation step as it happens, but doesn't suspend execution until
            an actual breakpoint is reached.  When this happens, the history of
            evaluation steps can be inspected.</para>
        </listitem>
        <listitem>
          <para>Exceptions (e.g. pattern matching failure and
            <literal>error</literal>) can be treated as breakpoints, to help
            locate the source of an exception in the program.</para>
        </listitem>
      </itemizedlist>
    </para>
daniel.is.fischer's avatar
daniel.is.fischer committed
1210

Simon Marlow's avatar
Simon Marlow committed
1211
    <para>There is currently no support for obtaining a &ldquo;stack
1212 1213 1214 1215 1216 1217
    trace&rdquo;, but the tracing and history features provide a
    useful second-best, which will often be enough to establish the
    context of an error.  For instance, it is possible to break
    automatically when an exception is thrown, even if it is thrown
    from within compiled code (see <xref
    linkend="ghci-debugger-exceptions" />).</para>
daniel.is.fischer's avatar
daniel.is.fischer committed
1218

Simon Marlow's avatar
Simon Marlow committed
1219 1220
    <sect2 id="breakpoints">
      <title>Breakpoints and inspecting variables</title>
daniel.is.fischer's avatar
daniel.is.fischer committed
1221

Simon Marlow's avatar
Simon Marlow committed
1222 1223 1224
      <para>Let's use quicksort as a running example.  Here's the code:</para>

<programlisting>
daniel.is.fischer's avatar
daniel.is.fischer committed
1225
qsort [] = []
Simon Marlow's avatar
Simon Marlow committed
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
qsort (a:as) = qsort left ++ [a] ++ qsort right
  where (left,right) = (filter (&lt;=a) as, filter (&gt;a) as)

main = print (qsort [8, 4, 0, 3, 1, 23, 11, 18])
</programlisting>

      <para>First, load the module into GHCi:</para>

<screen>
Prelude> :l qsort.hs
[1 of 1] Compiling Main             ( qsort.hs, interpreted )
Ok, modules loaded: Main.
*Main>
daniel.is.fischer's avatar
daniel.is.fischer committed
1239
      </screen>
Simon Marlow's avatar
Simon Marlow committed
1240 1241 1242 1243 1244 1245 1246 1247 1248

      <para>Now, let's set a breakpoint on the right-hand-side of the second
        equation of qsort:</para>

<programlisting>
*Main> :break 2
Breakpoint 0 activated at qsort.hs:2:15-46
*Main>
</programlisting>
daniel.is.fischer's avatar
daniel.is.fischer committed
1249

Simon Marlow's avatar
Simon Marlow committed
1250 1251 1252 1253
      <para>The command <literal>:break 2</literal> sets a breakpoint on line
        2 of the most recently-loaded module, in this case
        <literal>qsort.hs</literal>.   Specifically, it picks the
        leftmost complete subexpression on that line on which to set the
daniel.is.fischer's avatar
daniel.is.fischer committed
1254
        breakpoint, which in this case is the expression
Simon Marlow's avatar
Simon Marlow committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
        <literal>(qsort left ++ [a] ++ qsort right)</literal>.</para>

      <para>Now, we run the program:</para>

<programlisting>
*Main> main
Stopped at qsort.hs:2:15-46
_result :: [a]
a :: a
left :: [a]
right :: [a]
[qsort.hs:2:15-46] *Main>
</programlisting>

      <para>Execution has stopped at the breakpoint.  The prompt has changed to
        indicate that we are currently stopped at a breakpoint, and the location:
        <literal>[qsort.hs:2:15-46]</literal>.  To further clarify the
        location, we can use the <literal>:list</literal> command:</para>

<programlisting>
daniel.is.fischer's avatar
daniel.is.fischer committed
1275 1276
[qsort.hs:2:15-46] *Main> :list
1  qsort [] = []
Simon Marlow's avatar
Simon Marlow committed
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
2  qsort (a:as) = qsort left ++ [a] ++ qsort right
3    where (left,right) = (filter (&lt;=a) as, filter (&gt;a) as)
</programlisting>

      <para>The <literal>:list</literal> command lists the source code around
        the current breakpoint.  If your output device supports it, then GHCi
        will highlight the active subexpression in bold.</para>

      <para>GHCi has provided bindings for the free variables<footnote><para>We
            originally provided bindings for all variables in scope, rather
            than just
            the free variables of the expression, but found that this affected
            performance considerably, hence the current restriction to just the
            free variables.</para>
        </footnote> of the expression
        on which the
        breakpoint was placed (<literal>a</literal>, <literal>left</literal>,
        <literal>right</literal>), and additionally a binding for the result of
        the expression (<literal>_result</literal>).  These variables are just
        like other variables that you might define in GHCi; you
        can use them in expressions that you type at the prompt, you can ask
        for their types with <literal>:type</literal>, and so on.  There is one
        important difference though: these variables may only have partial
        types.  For example, if we try to display the value of
        <literal>left</literal>:</para>

<screen>
[qsort.hs:2:15-46] *Main> left

&lt;interactive&gt;:1:0:
    Ambiguous type variable `a' in the constraint:
      `Show a' arising from a use of `print' at &lt;interactive&gt;:1:0-3
    Cannot resolve unknown runtime types: a
    Use :print or :force to determine these types
</screen>

      <para>This is because <literal>qsort</literal> is a polymorphic function,
        and because GHCi does not carry type information at runtime, it cannot
        determine the runtime types of free variables that involve type
        variables.  Hence, when you ask to display <literal>left</literal> at
        the prompt, GHCi can't figure out which instance of
        <literal>Show</literal> to use, so it emits the type error above.</para>

      <para>Fortunately, the debugger includes a generic printing command,
        <literal>:print</literal>, which can inspect the actual runtime value of a
        variable and attempt to reconstruct its type.  If we try it on
        <literal>left</literal>:</para>

<screen>
1326
[qsort.hs:2:15-46] *Main> :set -fprint-evld-with-show
Simon Marlow's avatar
Simon Marlow committed
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
[qsort.hs:2:15-46] *Main> :print left
left = (_t1::[a])
</screen>

      <para>This isn't particularly enlightening.  What happened is that
        <literal>left</literal> is bound to an unevaluated computation (a
        suspension, or <firstterm>thunk</firstterm>), and
        <literal>:print</literal> does not force any evaluation.  The idea is
        that <literal>:print</literal> can be used to inspect values at a
        breakpoint without any unfortunate side effects.  It won't force any
        evaluation, which could cause the program to give a different answer
        than it would normally, and hence it won't cause any exceptions to be
        raised, infinite loops, or further breakpoints to be triggered (see
        <xref linkend="nested-breakpoints" />).
        Rather than forcing thunks, <literal>:print</literal>
        binds each thunk to a fresh variable beginning with an
        underscore, in this case
        <literal>_t1</literal>.</para>

1346 1347 1348
      <para>The flag <literal>-fprint-evld-with-show</literal> instructs
      <literal>:print</literal> to reuse
      available <literal>Show</literal> instances when possible. This happens
daniel.is.fischer's avatar
daniel.is.fischer committed
1349
      only when the contents of the variable being inspected
1350 1351 1352
      are completely evaluated.</para>


Simon Marlow's avatar
Simon Marlow committed
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
      <para>If we aren't concerned about preserving the evaluatedness of a
        variable, we can use <literal>:force</literal> instead of
        <literal>:print</literal>.  The <literal>:force</literal> command
        behaves exactly like <literal>:print</literal>, except that it forces
        the evaluation of any thunks it encounters:</para>

<screen>
[qsort.hs:2:15-46] *Main> :force left
left = [4,0,3,1]
</screen>

      <para>Now, since <literal>:force</literal> has inspected the runtime
        value of <literal>left</literal>, it has reconstructed its type.  We
        can see the results of this type reconstruction:</para>

<screen>
[qsort.hs:2:15-46] *Main> :show bindings
_result :: [Integer]
a :: Integer
left :: [Integer]
right :: [Integer]
_t1 :: [Integer]
</screen>

      <para>Not only do we now know the type of <literal>left</literal>, but
        all the other partial types have also been resolved.  So we can ask
        for the value of <literal>a</literal>, for example:</para>

<screen>
[qsort.hs:2:15-46] *Main> a
8
</screen>
daniel.is.fischer's avatar
daniel.is.fischer committed
1385

Simon Marlow's avatar
Simon Marlow committed
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
      <para>You might find it useful to use Haskell's
        <literal>seq</literal> function to evaluate individual thunks rather
        than evaluating the whole expression with <literal>:force</literal>.
        For example:</para>

<screen>
[qsort.hs:2:15-46] *Main> :print right
right = (_t1::[Integer])
[qsort.hs:2:15-46] *Main> seq _t1 ()
()
[qsort.hs:2:15-46] *Main> :print right
right = 23 : (_t2::[Integer])
</screen>

      <para>We evaluated only the <literal>_t1</literal> thunk, revealing the
        head of the list, and the tail is another thunk now bound to
        <literal>_t2</literal>.  The <literal>seq</literal> function is a
        little inconvenient to use here, so you might want to use
        <literal>:def</literal> to make a nicer interface (left as an exercise
        for the reader!).</para>

      <para>Finally, we can continue the current execution:</para>

<screen>
[qsort.hs:2:15-46] *Main> :continue
Stopped at qsort.hs:2:15-46
_result :: [a]
a :: a
left :: [a]
right :: [a]
daniel.is.fischer's avatar
daniel.is.fischer committed
1416
[qsort.hs:2:15-46] *Main>
Simon Marlow's avatar
Simon Marlow committed
1417 1418 1419 1420 1421
</screen>

      <para>The execution continued at the point it previously stopped, and has
        now stopped at the breakpoint for a second time.</para>

1422

Ian Lynagh's avatar
Typo  
Ian Lynagh committed
1423
      <sect3 id="setting-breakpoints">
Simon Marlow's avatar
Simon Marlow committed
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
        <title>Setting breakpoints</title>

        <para>Breakpoints can be set in various ways.  Perhaps the easiest way to
          set a breakpoint is to name a top-level function:</para>

<screen>
   :break <replaceable>identifier</replaceable>
</screen>

      <para>Where <replaceable>identifier</replaceable> names any top-level
        function in an interpreted module currently loaded into GHCi (qualified
        names may be used).  The breakpoint will be set on the body of the
        function, when it is fully applied but before any pattern matching has
        taken place.</para>

      <para>Breakpoints can also be set by line (and optionally column)
        number:</para>

<screen>
   :break <replaceable>line</replaceable>
   :break <replaceable>line</replaceable> <replaceable>column</replaceable>
   :break <replaceable>module</replaceable> <replaceable>line</replaceable>
daniel.is.fischer's avatar
daniel.is.fischer committed
1446
   :break <replaceable>module</replaceable> <replaceable>line</replaceable> <replaceable>column</replaceable>
Simon Marlow's avatar
Simon Marlow committed
1447 1448 1449 1450 1451
</screen>

      <para>When a breakpoint is set on a particular line, GHCi sets the
        breakpoint on the
        leftmost subexpression that begins and ends on that line.  If two
daniel.is.fischer's avatar
daniel.is.fischer committed
1452
        complete subexpressions start at the same
Simon Marlow's avatar
Simon Marlow committed
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
        column, the longest one is picked.  If there is no complete
        subexpression on the line, then the leftmost expression starting on
        the line is picked, and failing that the rightmost expression that
        partially or completely covers the line.</para>

      <para>When a breakpoint is set on a particular line and column, GHCi
        picks the smallest subexpression that encloses that location on which
        to set the breakpoint.  Note: GHC considers the TAB character to have a
        width of 1, wherever it occurs; in other words it counts
          characters, rather than columns.  This matches what some editors do,
          and doesn't match others.  The best advice is to avoid tab
          characters in your source code altogether (see
          <option>-fwarn-tabs</option> in <xref linkend="options-sanity"
daniel.is.fischer's avatar
daniel.is.fischer committed
1466
            />).</para>
Simon Marlow's avatar
Simon Marlow committed
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485

      <para>If the module is omitted, then the most recently-loaded module is
        used.</para>

      <para>Not all subexpressions are potential breakpoint locations.  Single
        variables are typically not considered to be breakpoint locations
        (unless the variable is the right-hand-side of a function definition,
        lambda, or case alternative).  The rule of thumb is that all redexes
        are breakpoint locations, together with the bodies of functions,
        lambdas, case alternatives and binding statements.  There is normally
        no breakpoint on a let expression, but there will always be a
        breakpoint on its body, because we are usually interested in inspecting
        the values of the variables bound by the let.</para>

      </sect3>
      <sect3>
        <title>Listing and deleting breakpoints</title>

        <para>The list of breakpoints currently enabled can be displayed using
1486
          <literal>:show&nbsp;breaks</literal>:</para>
Simon Marlow's avatar
Simon Marlow committed
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
<screen>
*Main> :show breaks
[0] Main qsort.hs:1:11-12
[1] Main qsort.hs:2:15-46
</screen>

        <para>To delete a breakpoint, use the <literal>:delete</literal>
          command with the number given in the output from <literal>:show&nbsp;breaks</literal>:</para>

<screen>
*Main> :delete 0
*Main> :show breaks
[1] Main qsort.hs:2:15-46
daniel.is.fischer's avatar
daniel.is.fischer committed
1500
</screen>
Simon Marlow's avatar
Simon Marlow committed
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511

        <para>To delete all breakpoints at once, use <literal>:delete *</literal>.</para>

    </sect3>
    </sect2>

    <sect2 id="single-stepping">
      <title>Single-stepping</title>

      <para>Single-stepping is a great way to visualise the execution of your
        program, and it is also a useful tool for identifying the source of a
daniel.is.fischer's avatar
daniel.is.fischer committed
1512
        bug. GHCi offers two variants of stepping. Use
1513 1514
	<literal>:step</literal>  to enable all the
        breakpoints in the program, and execute until the next breakpoint is
1515 1516 1517 1518
        reached. Use <literal>:steplocal</literal> to limit the set
	of enabled breakpoints to those in the current top level function.
	Similarly, use <literal>:stepmodule</literal> to single step only on
	breakpoints contained in the current module.
1519
	For example:</para>
Simon Marlow's avatar
Simon Marlow committed
1520 1521 1522 1523 1524 1525 1526 1527

<screen>
*Main> :step main
Stopped at qsort.hs:5:7-47
_result :: IO ()
</screen>

      <para>The command <literal>:step
1528
        <replaceable>expr</replaceable></literal> begins the evaluation of
Simon Marlow's avatar
Simon Marlow committed
1529
        <replaceable>expr</replaceable> in single-stepping mode.  If
1530
        <replaceable>expr</replaceable> is omitted, then it single-steps from
daniel.is.fischer's avatar
daniel.is.fischer committed
1531
        the current breakpoint. <literal>:stepover</literal>
1532
        works similarly.</para>
Simon Marlow's avatar
Simon Marlow committed