ghci.xml 97.1 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>
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
Ian Lynagh's avatar
Ian Lynagh committed
31
GHCi, version 6.8.1: http://www.haskell.org/ghc/  :? for help
32
Loading package base ... linking ... done.
33 34 35 36
Prelude> 
</screen>

    <para>There may be a short pause while GHCi loads the prelude and
37 38 39
    standard libraries, after which the prompt is shown. As the banner
    says, you can type <literal>:?</literal> to see the list of commands
    available, and a half line description of each of them.</para>
40 41 42 43 44 45 46 47 48 49 50 51

    <para>We'll explain most of these commands as we go along.  For
    Hugs users: many things work the same as in Hugs, so you should be
    able to get going straight away.</para>

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

<screen>
Prelude> 1+2
3
52
Prelude> let x = 42 in x / 9
53 54 55 56 57 58 59 60 61
4.666666666666667
Prelude> 
</screen>

    <para>GHCi interprets the whole line as an expression to evaluate.
    The expression may not span several lines - as soon as you press
    enter, GHCi will attempt to evaluate it.</para>
  </sect1>

62
  <sect1 id="loading-source-files">
63 64 65
    <title>Loading source files</title>

    <para>Suppose we have the following Haskell source code, which we
66
    place in a file <filename>Main.hs</filename>:</para>
67 68 69 70 71 72 73 74

<programlisting>
main = print (fac 20)

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

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    <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>

93 94
    <para>To load a Haskell source file into GHCi, use the
    <literal>:load</literal> command:</para>
95
    <indexterm><primary><literal>:load</literal></primary></indexterm>
96 97 98 99 100

<screen>
Prelude> :load Main
Compiling Main             ( Main.hs, interpreted )
Ok, modules loaded: Main.
101
*Main>
102 103 104
</screen>

    <para>GHCi has loaded the <literal>Main</literal> module, and the
105
    prompt has changed to &ldquo;<literal>*Main></literal>&rdquo; to
106
    indicate that the current context for expressions typed at the
107 108
    prompt is the <literal>Main</literal> module we just loaded (we'll
    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>
111 112

<screen>
113
*Main> fac 17
114 115 116 117 118 119 120 121 122 123 124 125
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>

126
    <sect2 id="ghci-modules-filenames">
127
      <title>Modules vs. filenames</title>
128 129
      <indexterm><primary>modules</primary><secondary>and filenames</secondary></indexterm>
      <indexterm><primary>filenames</primary><secondary>of modules</secondary></indexterm>
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
      
      <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>

147 148 149 150 151 152 153
      <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
154
      linkend="ghci-cmd-line-options"/>)<footnote><para>Note that in
155
      GHCi, and <option>&ndash;&ndash;make</option> mode, the <option>-i</option>
156 157 158 159
      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
160
      linkend="search-path"/>.</para> </footnote></para>
161

162 163 164 165 166 167 168 169 170
      <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>
171 172 173 174
    </sect2>

    <sect2>
      <title>Making changes and recompilation</title>
175
      <indexterm><primary><literal>:reload</literal></primary></indexterm>
176 177 178 179 180 181 182

      <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
183
      compilation setting (see <xref linkend="recomp"/>).</para>
184 185 186 187 188
    </sect2>
  </sect1>

  <sect1 id="ghci-compiled">
    <title>Loading compiled code</title>
189
    <indexterm><primary>compiled code</primary><secondary>in GHCi</secondary></indexterm>
190 191 192 193 194

    <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
195 196
    copy of the <literal>base</literal> package, which contains the
    <literal>Prelude</literal>.</para>
197 198 199 200 201 202 203 204 205 206 207 208 209

    <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>

    <para>When loading up source files with <literal>:load</literal>,
    GHCi 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,
210
    and A imports both B &amp; C:</para>
211 212 213 214 215 216 217 218 219 220 221 222
<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 )
223
Compiling C                ( C.hs, interpreted )
224 225
Compiling A                ( A.hs, interpreted )
Ok, modules loaded: A, B, C, D.
226
*Main>
227 228
</screen>

229 230 231 232
    <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
233 234
    is unchanged since the last compilation.</para>

235 236 237 238 239 240 241 242 243 244 245 246 247
    <para>At any time you can use the command 
    <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>

248
    <para>If we now modify the source of D (or pretend to: using the Unix
249 250 251 252 253
    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>
254 255
*Main> :! touch D.hs
*Main> :reload
256 257
Compiling D                ( D.hs, interpreted )
Ok, modules loaded: A, B, C, D.
258
*Main> 
259 260 261 262 263 264 265 266 267 268
</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>
269 270
*Main> :! ghc -c C.hs
*Main> :load A
271 272
Compiling D                ( D.hs, interpreted )
Compiling B                ( B.hs, interpreted )
273
Compiling C                ( C.hs, interpreted )
274 275 276 277 278 279 280 281 282 283 284
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>
285 286
*Main> :! ghc -c D.hs
*Main> :reload
287 288 289 290 291 292 293 294
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>
295
*Main> :load A
296 297 298 299 300 301
Compiling B                ( B.hs, interpreted )
Compiling A                ( A.hs, interpreted )
Ok, modules loaded: A, B, C, D.
</screen>

    <para>HINT: since GHCi will only use a compiled object file if it
Ian Lynagh's avatar
Ian Lynagh committed
302
    can be sure that the compiled version is up-to-date, a good technique
303
    when working on a large program is to occasionally run
304
    <literal>ghc &ndash;&ndash;make</literal> to compile the whole project (say
305
    before you go for lunch :-), then continue working in the
306
    interpreter.  As you modify code, the changed modules will be
307 308 309 310 311
    interpreted, but the rest of the project will remain
    compiled.</para>

  </sect1>

312
  <sect1 id="interactive-evaluation">
313 314 315
    <title>Interactive evaluation at the prompt</title>

    <para>When you type an expression at the prompt, GHCi immediately
316 317 318 319 320 321 322 323 324 325
    evaluates and prints the result:
<screen>
Prelude> reverse "hello"
"olleh"
Prelude> 5+5
10
</screen>
</para>

<sect2><title>I/O actions at the prompt</title>
326

327 328 329 330
<para>GHCi does more than simple expression evaluation at the prompt.
If you type something of type <literal>IO a</literal> for some
    <literal>a</literal>, then GHCi <emphasis>executes</emphasis> it
    as an IO-computation.
331 332 333 334 335 336
<screen>
Prelude> "hello"
"hello"
Prelude> putStrLn "hello"
hello
</screen>
337 338 339 340 341 342 343 344 345 346 347 348 349 350
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"
351
</screen>
352
</para></sect2>
353

354
    <sect2 id="ghci-stmts">
355 356 357 358 359 360 361 362
      <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>
      
      <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>
363

364 365 366 367 368
      <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.
369
<screen>
370 371 372 373 374
Prelude> x &lt;- return 42
42
Prelude> print x
42
Prelude>
375
</screen>
376 377 378 379 380 381
      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>
382

383 384 385 386 387 388 389 390 391 392 393 394 395
      <para>GHCi will print the result of a statement if and only if: 
	<itemizedlist>
	  <listitem>
	    <para>The statement is not a binding, or it is a monadic binding 
	      (<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>
396 397 398 399 400 401 402
      The automatic printing of binding results can be supressed with
      <option>:set -fno-print-bind-result</option> (this does not
      supress printing the result of non-binding statements).
      <indexterm><primary><option>-fno-print-bind-result</option></primary></indexterm><indexterm><primary><option>-fprint-bind-result</option></primary></indexterm>.
      You might want to do this to prevent the result of binding
      statements from being fully evaluated by the act of printing
      them, for example.</para>
403

404 405 406 407
      <para>Of course, you can also bind normal non-IO expressions
      using the <literal>let</literal>-statement:</para>
<screen>
Prelude> let x = 42
408
Prelude> x
409 410 411
42
Prelude>
</screen>
412
      <para>Another important difference between the two types of binding
413 414 415 416 417 418 419 420 421 422
      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>
423 424 425 426

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

427 428 429 430 431 432
      <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>

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
      <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>
462

463
    </sect2>
464 465 466 467

    <sect2 id="ghci-scope">
      <title>What's really in scope at the prompt?</title> 

468 469 470 471 472
      <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>
473

474
<screen>Prelude></screen>
475

476 477 478
      <para>Which indicates that everything from the module
      <literal>Prelude</literal> is currently in scope.  If we now
      load a file into GHCi, the prompt will change:</para>
479

480 481 482 483 484
<screen>
Prelude> :load Main.hs
Compiling Main             ( Main.hs, interpreted )
*Main>
</screen>
485

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
      <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
      that is in effect at the prompt.  For technical reasons, GHCi
      can only support the <literal>*</literal>-form for modules which
      are interpreted, so compiled modules and package modules can
      only contribute their exports to the current scope.</para>

      <para>The scope is manipulated using the
      <literal>:module</literal> command.  For example, if the current
      scope is <literal>Prelude</literal>, then we can bring into
      scope the exports from the module <literal>IO</literal> like
      so:</para>
516

517 518
<screen>
Prelude> :module +IO
Ian Lynagh's avatar
Ian Lynagh committed
519
Prelude IO> hPutStrLn stdout "hello\n"
520
hello
Ian Lynagh's avatar
Ian Lynagh committed
521
Prelude IO>
522 523
</screen>

524 525 526
      <para>(Note: you can use <literal>import M</literal> as an
      alternative to <literal>:module +M</literal>, and
      <literal>:module</literal> can also be shortened to 
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
      <literal>:m</literal>). The full syntax of the
      <literal>:module</literal> command is:</para>

<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
      use this form and leave out <literal>Prelude</literal>, GHCi
      will assume that you really wanted the
      <literal>Prelude</literal> and add it in for you (if you don't
      want the <literal>Prelude</literal>, then ask to remove it with
      <literal>:m -Prelude</literal>).</para>

      <para>The scope is automatically set after a
      <literal>:load</literal> command, to the most recently loaded
      "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
553
      set to <literal>Prelude Bar</literal> (GHCi automatically adds
554 555 556 557 558 559 560 561 562 563
      <literal>Prelude</literal> if it isn't present and there aren't
      any <literal>*</literal>-form modules).</para>

      <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
564 565 566
      <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
567
        then GHCi will expand it to &ldquo;<literal>Just </literal>&rdquo;.
Ian Lynagh's avatar
Ian Lynagh committed
568 569
      </para>

570 571 572 573 574 575 576 577
      <sect3>
	<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
        package, and every module currently loaded into GHCi.</para>
      </sect3>
Ian Lynagh's avatar
Ian Lynagh committed
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

      <sect3>
        <title>The <literal>:main</literal> command</title>

        <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"]
</screen>

      </sect3>
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
    </sect2>
  

    <sect2>
      <title>The <literal>it</literal> variable</title>
      <indexterm><primary><literal>it</literal></primary>
      </indexterm>
      
      <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>
623 624 625 626
    <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
    <replaceable>e</replaceable> turns into 
Ian Lynagh's avatar
Ian Lynagh committed
627 628 629
<screen>
let it = <replaceable>e</replaceable>;
print it
630
</screen>
631 632 633 634 635 636 637
    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
638 639 640 641 642 643 644 645
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
646 647 648 649
</screen>

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

651
      <para>If the expression was instead of type <literal>IO a</literal> for
652 653 654 655 656
      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
657
Wed Mar 14 12:23:13 GMT 2001
658 659 660 661
Prelude> print it
Wed Mar 14 12:23:13 GMT 2001
</screen>

662 663
      <para>The corresponding translation for an IO-typed
      <replaceable>e</replaceable> is
Ian Lynagh's avatar
Ian Lynagh committed
664 665
<screen>
it &lt;- <replaceable>e</replaceable>
666 667 668
</screen>
      </para>

669 670 671 672 673
      <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>
674

675
    <sect2 id="extended-default-rules">
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
      <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>
      (which is what GHCi computes here) has type <literal>Show a => a</literal> and how that displays depends 
      on the type <literal>a</literal>.  For example:
<programlisting>
  ghci> (reverse []) :: String
  ""
  ghci> (reverse []) :: [Int]
  []
</programlisting>
    However, it is tiresome for the user to have to specify the type, so GHCi extends Haskell's type-defaulting
694 695 696 697
    rules (Section 4.3.4 of the Haskell 98 Report (Revised)) as follows.  The
    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
    type variable if 
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
    <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
718
    <literal>-XExtendedDefaultRules</literal> flag is given,
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 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
    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
767 768
    (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
769 770
    <literal>Integer</literal> then ghci gives an error when running a
    printf.
771 772
   </para>
    </sect2>
773 774
  </sect1>

Simon Marlow's avatar
Simon Marlow committed
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 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 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 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 1097 1098 1099 1100 1101 1102 1103 1104 1105 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 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 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 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 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
  <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
      default: no flags are required to enable the debugging facilities.  There
      is one major restriction: breakpoints and single-stepping are only
      available in <emphasis>interpreted</emphasis> modules; compiled code is
      invisible to the debugger.</para>

    <para>The debugger provides the following:
    <itemizedlist>
        <listitem>
          <para>The abilty to set a <firstterm>breakpoint</firstterm> on a
            function definition or expression in the program.  When the function
            is called, or the expression evaluated, GHCi suspends 
            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>
      
    <para>There is currently no support for obtaining a &ldquo;stack
      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.</para>
      
    <sect2 id="breakpoints">
      <title>Breakpoints and inspecting variables</title>
      
      <para>Let's use quicksort as a running example.  Here's the code:</para>

<programlisting>
qsort [] = [] 
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>
      </screen>       

      <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>
      
      <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
        breakpoint, which in this case is the expression 
        <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>
[qsort.hs:2:15-46] *Main> :list 
1  qsort [] = [] 
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>
[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>

      <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>
      
      <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]
[qsort.hs:2:15-46] *Main> 
</screen>

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

      <sect3 id="setting-breakpoings">
        <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>
   :break <replaceable>module</replaceable> <replaceable>line</replaceable> <replaceable>column</replaceable> 
</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
        complete subexpressions start at the same 
        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"
            />).</para> 

      <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
          <literal>:show&nbsp;breaks</literal></para>:
<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
</screen>        

        <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
        bug.  The concept is simple: single-stepping enables all the
        breakpoints in the program and executes until the next breakpoint is
        reached, at which point you can single-step again, or continue
        normally.  For example:</para>

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

      <para>The command <literal>:step
          <replaceable>expr</replaceable></literal> begins the evaluation of
        <replaceable>expr</replaceable> in single-stepping mode.  If
        <replaceable>expr</replaceable> is ommitted, then it single-steps from
        the current breakpoint.</para>

      <para>The <literal>:list</literal> command is particularly useful when
        single-stepping, to see where you currently are:</para>

<screen>
[qsort.hs:5:7-47] *Main> :list
4  
5  main = print (qsort [8, 4, 0, 3, 1, 23, 11, 18])
6  
[qsort.hs:5:7-47] *Main>
</screen>

      <para>In fact, GHCi provides a way to run a command when a breakpoint is
        hit, so we can make it automatically do
        <literal>:list</literal>:</para>

<screen>
[qsort.hs:5:7-47] *Main> :set stop :list
[qsort.hs:5:7-47] *Main> :step
Stopped at qsort.hs:5:14-46
_result :: [Integer]
4  
5  main = print (qsort [8, 4, 0, 3, 1, 23, 11, 18])
6  
[qsort.hs:5:14-46] *Main>
</screen>
    </sect2>

    <sect2 id="nested-breakpoints">
      <title>Nested breakpoints</title>
      <para>When GHCi is stopped at a breakpoint, and an expression entered at
        the prompt triggers a
        second breakpoint, the new breakpoint becomes the &ldquo;current&rdquo;
      one, and the old one is saved on a stack.  An arbitrary number of
        breakpoint contexts can be built up in this way.  For example:</para>

<screen>
[qsort.hs:2:15-46] *Main> :st qsort [1,3]
Stopped at qsort.hs:(1,0)-(3,55)
_result :: [a]
... [qsort.hs:(1,0)-(3,55)] *Main>
</screen>

      <para>While stopped at the breakpoint on line 2 that we set earlier, we
        started a new evaluation with <literal>:step qsort [1,3]</literal>.
        This new evaluation stopped after one step (at the definition of
        <literal>qsort</literal>).  The prompt has changed, now prefixed with
        <literal>...</literal>, to indicate that there are saved breakpoints
        beyond the current one.  To see the stack of contexts, use
        <literal>:show context</literal>:</para>

<screen>
... [qsort.hs:(1,0)-(3,55)] *Main> :show context
--> main
  Stopped at qsort.hs:2:15-46
--> qsort [1,3]
  Stopped at qsort.hs:(1,0)-(3,55)
... [qsort.hs:(1,0)-(3,55)] *Main>
</screen>

        <para>To abandon the current evaluation, use
        <literal>:abandon</literal>:</para>

<screen>
... [qsort.hs:(1,0)-(3,55)] *Main> :abandon
[qsort.hs:2:15-46] *Main> :abandon
*Main>
</screen>
    </sect2>

    <sect2 id="ghci-debugger-result">
      <title>The <literal>_result</literal> variable</title>
      <para>When stopped at a breakpoint or single-step, GHCi binds the
        variable <literal>_result</literal> to the value of the currently
        active expression.  The value of <literal>_result</literal> is
        presumably not available yet, because we stopped its evaluation, but it
        can be forced: if the type is known and showable, then just entering
        <literal>_result</literal> at the prompt will show it.  However,
        there's one caveat to doing this: evaluating <literal>_result</literal>
        will be likely to trigger further breakpoints, starting with the
        breakpoint we are currently stopped at (if we stopped at a real
        breakpoint, rather than due to <literal>:step</literal>).  So it will
        probably be necessary to issue a <literal>:continue</literal>
        immediately when evaluating <literal>_result</literal>.  Alternatively,
        you can use <literal>:force</literal> which ignores breakpoints.</para>
    </sect2>

    <sect2 id="tracing">
      <title>Tracing and history</title>

      <para>A question that we often want to ask when debugging a program is
        &ldquo;how did I get here?&rdquo;.  Traditional imperative debuggers
        usually provide some kind of stack-tracing feature that lets you see
        the stack of active function calls (sometimes called the &ldquo;lexical
        call stack&rdquo;), describing a path through the code
        to the current location.  Unfortunately this is hard to provide in
        Haskell, because execution proceeds on a demand-driven basis, rather
        than a depth-first basis as in strict languages.  The
        &ldquo;stack&ldquo; in GHC's execution engine bears little
        resemblance to the lexical call stack.  Ideally GHCi would maintain a
        separate lexical call stack in addition to the dynamic call stack, and
        in fact this is exactly
        what our profiling system does (<xref linkend="profiling" />), and what
        some other Haskell debuggers do.  For the time being, however, GHCi
        doesn't maintain a lexical call stack (there are some technical
        challenges to be overcome).  Instead, we provide a way to backtrack from a
        breakpoint to previous evaluation steps: essentially this is like
        single-stepping backwards, and should in many cases provide enough
        information to answer the &ldquo;how did I get here?&rdquo;
        question.</para>

      <para>To use tracing, evaluate an expression with the
        <literal>:trace</literal> command.  For example, if we set a breakpoint
        on the base case of <literal>qsort</literal>:</para>

<screen>
*Main&gt; :list qsort
1  qsort [] = [] 
2  qsort (a:as) = qsort left ++ [a] ++ qsort right
3    where (left,right) = (filter (&lt;=a) as, filter (&gt;a) as)
4  
*Main&gt; :b 1
Breakpoint 1 activated at qsort.hs:1:11-12
*Main&gt; 
</screen>

      <para>and then run a small <literal>qsort</literal> with
        tracing:</para>

<screen>
*Main> :trace qsort [3,2,1]
Stopped at qsort.hs:1:11-12
_result :: [a]
[qsort.hs:1:11-12] *Main>
</screen>

      <para>We can now inspect the history of evaluation steps:</para>

<screen>
[qsort.hs:1:11-12] *Main> :hist
-1  : qsort.hs:3:24-38
-2  : qsort.hs:3:23-55
-3  : qsort.hs:(1,0)-(3,55)
-4  : qsort.hs:2:15-24
-5  : qsort.hs:2:15-46
-6  : qsort.hs:3:24-38
-7  : qsort.hs:3:23-55
-8  : qsort.hs:(1,0)-(3,55)
-9  : qsort.hs:2:15-24
-10 : qsort.hs:2:15-46
-11 : qsort.hs:3:24-38
-12 : qsort.hs:3:23-55
-13 : qsort.hs:(1,0)-(3,55)
-14 : qsort.hs:2:15-24
-15 : qsort.hs:2:15-46
-16 : qsort.hs:(1,0)-(3,55)
&lt;end of history&gt;
</screen>

      <para>To examine one of the steps in the history, use
        <literal>:back</literal>:</para>

<screen>
[qsort.hs:1:11-12] *Main> :back
Logged breakpoint at qsort.hs:3:24-38
_result :: [a]
as :: [a]
a :: a
[-1: qsort.hs:3:24-38] *Main> 
</screen>

      <para>Note that the local variables at each step in the history have been
        preserved, and can be examined as usual.  Also note that the prompt has
        changed to indicate that we're currently examining the first step in
        the history: <literal>-1</literal>.  The command
        <literal>:forward</literal> can be used to traverse forward in the
        history.</para>

      <para>The <literal>:trace</literal> command can be used with or without
        an expression.  When used without an expression, tracing begins from
        the current breakpoint, just like <literal>:step</literal>.</para>

      <para>The history is only available when
        using <literal>:trace</literal>; the reason for this is we found that
        logging each breakpoint in the history cuts performance by a factor of
        2 or more.  GHCi remembers the last 50 steps in the history (perhaps in
        the future we'll make this configurable).</para>
    </sect2>

    <sect2 id="ghci-debugger-exceptions">
      <title>Debugging exceptions</title>
      <para>Another common question that comes up when debugging is
        &ldquo;where did this exception come from?&rdquo;.  Exceptions such as
        those raised by <literal>error</literal> or <literal>head []</literal>
        have no context information attached to them.  Finding which
        particular call to <literal>head</literal> in your program resulted in
        the error can be a painstaking process, usually involving
Simon Marlow's avatar
Simon Marlow committed
1322 1323 1324
        <literal>Debug.Trace.trace</literal>, or compiling with
        profiling and using <literal>+RTS -xc</literal> (see <xref
          linkend="prof-time-options" />).</para>
Simon Marlow's avatar
Simon Marlow committed
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 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 1385 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 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497

      <para>The GHCi debugger offers a way to hopefully shed some light on
        these errors quickly and without modifying or recompiling the source
        code.  One way would be to set a breakpoint on the location in the
        source code that throws the exception, and then use
        <literal>:trace</literal> and <literal>:history</literal> to establish
        the context.  However, <literal>head</literal> is in a library and
        we can't set a breakpoint on it directly.  For this reason, GHCi
        provides the flag <literal>-fbreak-on-exception</literal> which causes
        the evaluator to stop when an exception is thrown, just as it does when
        a breakpoint is hit.  This is only really useful in conjunction with
        <literal>:trace</literal>, in order to log the steps leading up to the
        exception.  For example:</para>

<screen>
*Main> :set -fbreak-on-exception
*Main> :trace qsort ("abc" ++ undefined)
"Stopped at &lt;exception thrown&gt;
_exception :: e
[&lt;exception thrown&gt;] *Main&gt; :hist
-1  : qsort.hs:3:24-38
-2  : qsort.hs:3:23-55
-3  : qsort.hs:(1,0)-(3,55)
-4  : qsort.hs:2:15-24
-5  : qsort.hs:2:15-46
-6  : qsort.hs:(1,0)-(3,55)
&lt;end of history&gt;
[&lt;exception thrown&gt;] *Main&gt; :back
Logged breakpoint at qsort.hs:3:24-38
_result :: [a]
as :: [a]
a :: a
[-1: qsort.hs:3:24-38] *Main&gt; :force as
*** Exception: Prelude.undefined
[-1: qsort.hs:3:24-38] *Main&gt; :print as
as = 'b' : 'c' : (_t1::[Char])
</screen>

      <para>The exception itself is bound to a new variable,
        <literal>_exception</literal>.</para>

      <para>Breaking on exceptions is particularly useful for finding out what
        your program was doing when it was in an infinite loop.  Just hit
        Control-C, and examine the history to find out what was going
        on.</para>
    </sect2>

    <sect2><title>Example: inspecting functions</title>
      <para>
        It is possible to use the debugger to examine function values. 
        When we are at a breakpoint and a function is in scope, the debugger
        cannot show 
        you the source code for it; however, it is possible to get some 
        information by applying it to some arguments and  observing the result. 
      </para>

      <para>
        The process is slightly complicated when the binding is polymorphic. 
        We show the process by means of an example.
        To keep things simple, we will use the well known <literal>map</literal> function:
<programlisting>
import Prelude hiding (map)

map :: (a->b) -> a -> b
map f [] = []
map f (x:xs) = f x : map f xs
</programlisting>
      </para>

      <para>
        We set a breakpoint on <literal>map</literal>, and call it.
<screen>
*Main> :break 5
Breakpoint 0 activated at  map.hs:5:15-28
*Main> map Just [1..5]
Stopped at map.hs:(4,0)-(5,12)
_result :: [b]
x :: a
f :: a -> b
xs :: [a]
</screen>
      GHCi tells us that, among other bindings, <literal>f</literal> is in scope. 
      However, its type is not fully known yet,  
      and thus it is not possible to apply it to any 
      arguments. Nevertheless, observe that the type of its first argument is the
      same as the type of <literal>x</literal>, and its result type is shared
        with <literal>_result</literal>.
      </para>

      <para>
        As we demonstrated earlier (<xref linkend="breakpoints" />),  the
        debugger has some intelligence built-in to update the type of 
        <literal>f</literal> whenever the types of <literal>x</literal> or 
        <literal>_result</literal> are discovered.  So what we do in this
        scenario is
        force <literal>x</literal> a bit, in order to recover both its type 
      and the argument part of <literal>f</literal>.  
<screen>
*Main> seq x ()
*Main> :print x
x = 1
</screen>
      </para>
      <para>
        We can check now that as expected, the type of <literal>x</literal>
        has been reconstructed, and with it the 
        type of <literal>f</literal> has been too:</para>
<screen>
*Main> :t x
x :: Integer
*Main> :t f
f :: Integer -> b
</screen>
      <para>
        From here, we can apply f to any argument of type Integer and observe
        the results. 
<screen><![CDATA[
*Main> let b = f 10
*Main> :t b
b :: b
*Main> b
<interactive>:1:0:
    Ambiguous type variable `b' in the constraint:
      `Show b' arising from a use of `print' at <interactive>:1:0
*Main> :p b
b = (_t2::a)
*Main> seq b ()
()
*Main> :t b
b :: a
*Main> :p b
b = Just 10
*Main> :t b
b :: Maybe Integer
*Main> :t f
f :: Integer -> Maybe Integer
*Main> f 20
Just 20
*Main> map f [1..5]
[Just 1, Just 2, Just 3, Just 4, Just 5]
]]></screen>
      In the first application of <literal>f</literal>, we had to do 
      some more type reconstruction
      in order to recover the result type of <literal>f</literal>. 
      But after that, we are free to use 
      <literal>f</literal> normally.
     </para>
    </sect2>

    <sect2><title>Limitations</title>
      <itemizedlist>
        <listitem>
          <para>When stopped at a breakpoint, if you try to evaluate a variable
            that is already under evaluation, the second evaluation will hang.
            The reason is
            that GHC knows the variable is under evaluation, so the new
            evaluation just waits for the result before continuing, but of
            course this isn't going to happen because the first evaluation is
            stopped at a breakpoint. Control-C can interrupt the hung
            evaluation and return to the prompt.</para>
          <para>The most common way this can happen is when you're evaluating a
            CAF (e.g. main), stop at a breakpoint, and ask for the value of the
            CAF at the prompt again.</para>
        </listitem>
	<listitem><para>
	  Implicit parameters (see <xref linkend="implicit-parameters"/>) are only available 
	  at the scope of a breakpoint if there is a explicit type signature.
	</para>
        </listitem>
      </itemizedlist>
    </sect2>
  </sect1>

ross's avatar
ross committed
1498
  <sect1 id="ghci-invocation">
1499
    <title>Invoking GHCi</title>
1500
    <indexterm><primary>invoking</primary><secondary>GHCi</secondary></indexterm>
1501
    <indexterm><primary><option>&ndash;&ndash;interactive</option></primary></indexterm>
1502 1503

    <para>GHCi is invoked with the command <literal>ghci</literal> or
1504
    <literal>ghc &ndash;&ndash;interactive</literal>.  One or more modules or
1505 1506 1507 1508
    filenames can also be specified on the command line; this
    instructs GHCi to load the specified modules or filenames (and all
    the modules they depend on), just as if you had said
    <literal>:load <replaceable>modules</replaceable></literal> at the
Simon Marlow's avatar
Simon Marlow committed
1509
    GHCi prompt (see <xref linkend="ghci-commands" />).  For example, to
1510 1511
    start GHCi and load the program whose topmost module is in the
    file <literal>Main.hs</literal>, we could say:</para>
1512 1513 1514 1515 1516 1517

<screen>
$ ghci Main.hs
</screen>

    <para>Most of the command-line options accepted by GHC (see <xref
1518
    linkend="using-ghc"/>) also make sense in interactive mode.  The ones
1519 1520 1521 1522 1523 1524
    that don't make sense are mostly obvious; for example, GHCi
    doesn't generate interface files, so options related to interface
    file generation won't have any effect.</para>

    <sect2>
      <title>Packages</title>
1525
      <indexterm><primary>packages</primary><secondary>with GHCi</secondary></indexterm>
1526

1527
      <para>Most packages (see <xref linkend="using-packages"/>) are
1528 1529 1530 1531
      available without needing to specify any extra flags at all:
      they will be automatically loaded the first time they are
      needed.</para>

Simon Marlow's avatar
Simon Marlow committed
1532
      <para>For hidden packages, however, you need to request the
1533
      package be loaded by using the <literal>-package</literal> flag:</para>
1534 1535

<screen>
Ian Lynagh's avatar
Ian Lynagh committed
1536
$ ghci -package readline
1537 1538
   ___         ___ _
  / _ \ /\  /\/ __(_)
Ian Lynagh's avatar
Ian Lynagh committed
1539
 / /_\// /_/ / /  | |      GHC Interactive, version 6.6, for Haskell 98.
1540 1541 1542
/ /_\\/ __  / /___| |      http://www.haskell.org/ghc/
\____/\/ /_/\____/|_|      Type :? for help.

1543
Loading package base ... linking ... done.
Ian Lynagh's avatar
Ian Lynagh committed
1544
Loading package readline-1.0 ... linking ... done.
1545
Prelude> 
1546
</screen>
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556

      <para>The following command works to load new packages into a
      running GHCi:</para>

<screen>
Prelude> :set -package <replaceable>name</replaceable>
</screen>

      <para>But note that doing this will cause all currently loaded
      modules to be unloaded, and you'll be dumped back into the
1557
      <literal>Prelude</literal>.</para>
1558 1559 1560 1561
    </sect2>

    <sect2>
      <title>Extra libraries</title>
1562
      <indexterm><primary>libraries</primary><secondary>with GHCi</secondary></indexterm>
1563 1564 1565
      
      <para>Extra libraries may be specified on the command line using
      the normal <literal>-l<replaceable>lib</replaceable></literal>
1566 1567
      option.  (The term <emphasis>library</emphasis> here refers to
      libraries of foreign object code; for using libraries of Haskell
1568
      source code, see <xref linkend="ghci-modules-filenames"/>.) For
1569
      example, to load the &ldquo;m&rdquo; library:</para>
1570 1571 1572 1573 1574 1575 1576

<screen>
$ ghci -lm
</screen>

      <para>On systems with <literal>.so</literal>-style shared
      libraries, the actual library loaded will the
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
      <filename>lib<replaceable>lib</replaceable>.so</filename>.  GHCi
      searches the following places for libraries, in this order:</para>

      <itemizedlist>
	<listitem>
	  <para>Paths specified using the
          <literal>-L<replaceable>path</replaceable></literal>
          command-line option,</para>
	</listitem>
	<listitem>
	  <para>the standard library search path for your system,
ross's avatar
ross committed
1588
	  which on some systems may be overridden by setting the
1589 1590
	  <literal>LD_LIBRARY_PATH</literal> environment
	  variable.</para>
1591 1592
	</listitem>
      </itemizedlist>
1593 1594 1595 1596 1597

      <para>On systems with <literal>.dll</literal>-style shared
      libraries, the actual library loaded will be
      <filename><replaceable>lib</replaceable>.dll</filename>.  Again,
      GHCi will signal an error if it can't find the library.</para>
1598 1599 1600 1601 1602

      <para>GHCi can also load plain object files
      (<literal>.o</literal> or <literal>.obj</literal> depending on
      your platform) from the command-line.  Just add the name the
      object file to the command line.</para>
1603 1604 1605

      <para>Ordering of <option>-l</option> options matters: a library
      should be mentioned <emphasis>before</emphasis> the libraries it
1606
      depends on (see <xref linkend="options-linker"/>).</para>
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    </sect2>

  </sect1>

  <sect1 id="ghci-commands">
    <title>GHCi commands</title>

    <para>GHCi commands all begin with
    &lsquo;<literal>:</literal>&rsquo; and consist of a single command
    name followed by zero or more parameters.  The command name may be
1617 1618
    abbreviated, with ambiguities being resolved in favour of the more
    commonly used commands.</para>
1619 1620

    <variablelist>
Simon Marlow's avatar