ghci.rst 122 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
.. _ghci:

Using GHCi
==========

.. index::
   single: GHCi
   single: interpreter
   single: interactive
   single: Hugs
   single: Foreign Function Interface; GHCi support
   single: FFI; GHCi support

GHCi [1]_ is GHC's interactive environment, in which Haskell expressions
can be interactively evaluated and programs can be interpreted. If
you're familiar with `Hugs <http://www.haskell.org/hugs/>`__, then
you'll be right at home with GHCi. However, GHCi also has support for
interactively loading compiled code, as well as supporting all [2]_ the
language extensions that GHC provides. GHCi also includes an interactive
debugger (see :ref:`ghci-debugger`).

.. [1]
23
   The "i" stands for “Interactive”
24 25 26 27 28 29 30 31 32 33 34 35 36

.. [2]
   except ``foreign export``, at the moment


.. _ghci-introduction:

Introduction to GHCi
--------------------

Let's start with an example GHCi session. You can fire up GHCi with the
command ``ghci``:

37
.. code-block:: none
38 39

    $ ghci
40
    GHCi, version 8.y.z: https://www.haskell.org/ghc/  :? for help
41 42 43 44
    Prelude>

There may be a short pause while GHCi loads the prelude and standard
libraries, after which the prompt is shown. As the banner says, you can
45
type :ghci-cmd:`:?` to see the list of commands available, and a half line
46 47 48 49 50 51 52 53 54
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
:ref:`ghci-commands`.

Haskell expressions can be typed at the prompt:

.. index::
   single: prompt; GHCi

55
.. code-block:: none
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

    Prelude> 1+2
    3
    Prelude> let x = 42 in x / 9
    4.666666666666667
    Prelude>

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.

In Haskell, a ``let`` expression is followed by ``in``. However, in
GHCi, since the expression can also be interpreted in the ``IO`` monad,
a ``let`` binding with no accompanying ``in`` statement can be signalled
by an empty line, as in the above example.

72 73 74 75 76 77 78 79 80
Since GHC 8.0.1, you can bind values and functions to names without ``let`` statement:

.. code-block:: none

    Prelude> x = 42
    Prelude> x
    42
    Prelude>

81 82 83 84 85 86
.. _loading-source-files:

Loading source files
--------------------

Suppose we have the following Haskell source code, which we place in a
87
file ``Main.hs``: ::
88 89 90 91 92 93 94 95 96 97

    main = print (fac 20)

    fac 0 = 1
    fac n = n * fac (n-1)

You can save ``Main.hs`` anywhere you like, but if you save it somewhere
other than the current directory [3]_ then we will need to change to the
right directory in GHCi:

98
.. code-block:: none
99 100 101 102 103

    Prelude> :cd dir

where ⟨dir⟩ is the directory (or folder) in which you saved ``Main.hs``.

104
To load a Haskell source file into GHCi, use the :ghci-cmd:`:load` command:
105 106 107 108

.. index::
   single: :load

109
.. code-block:: none
110 111 112 113 114 115 116

    Prelude> :load Main
    Compiling Main             ( Main.hs, interpreted )
    Ok, modules loaded: Main.
    *Main>

GHCi has loaded the ``Main`` module, and the prompt has changed to
117
``*Main>`` to indicate that the current context for expressions
118 119 120 121
typed at the prompt is the ``Main`` module we just loaded (we'll explain
what the ``*`` means later in :ref:`ghci-scope`). So we can now type
expressions involving the functions from ``Main.hs``:

122
.. code-block:: none
123 124 125 126 127

    *Main> fac 17
    355687428096000

Loading a multi-module program is just as straightforward; just give the
128 129 130 131
name of the "topmost" module to the :ghci-cmd:`:load` command (hint:
:ghci-cmd:`:load` can be abbreviated to ``:l``). The topmost module will
normally be ``Main``, but it doesn't have to be. GHCi will discover which
modules are required, directly or indirectly, by the topmost module, and load
132 133 134 135 136 137 138 139 140
them all in dependency order.

.. [3]
   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 “Start” menu in
   Windows, then the current directory is probably something like
   ``C:\Documents and Settings\user name``.

141 142 143 144 145
.. ghc-flag:: -fshow-loaded-modules
    :shortdesc: Show the names of modules that GHCi loaded after a
                :ghci-cmd:`:load` command.
    :type: dynamic

146
    :default: off
147 148 149 150 151 152 153
    :since: 8.2.2

    Typically GHCi will show only the number of modules that it loaded after a
    :ghci-cmd:`:load` command. With this flag, GHC will also list the loaded
    modules' names. This was the default behavior prior to GHC 8.2.1 and can be
    useful for some tooling users.

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

.. _ghci-modules-filenames:

Modules vs. filenames
~~~~~~~~~~~~~~~~~~~~~

.. index::
   single: modules; and filenames
   single: filenames; of modules

Question: How does GHC find the filename which contains module ⟨M⟩?
Answer: it looks for the file ``M.hs``, or ``M.lhs``. 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.

There is one exception to this general rule: when you load a program
170
with :ghci-cmd:`:load`, or specify it when you invoke ``ghci``, you can give a
171 172 173 174 175
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 ``Main`` modules in the same directory
and you can't call them all ``Main.hs``.

176
The search path for finding source files is specified with the :ghc-flag:`-i`
177 178
option on the GHCi command line, like so:

179
.. code-block:: none
180 181 182

    ghci -idir1:...:dirn

183
or it can be set using the :ghci-cmd:`:set` command from within GHCi (see
184 185 186 187 188 189 190 191 192 193 194
:ref:`ghci-cmd-line-options`) [4]_

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
``Prelude`` and standard libraries such as ``IO`` and ``Complex``. 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.

.. [4]
195
   Note that in GHCi, and :ghc-flag:`--make` mode, the :ghc-flag:`-i` option is used to
196
   specify the search path for *source* files, whereas in standard
197
   batch-compilation mode the :ghc-flag:`-i` option is used to specify the
198 199 200 201 202 203 204 205 206 207
   search path for interface files, see :ref:`search-path`.


Making changes and recompilation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. index::
   single: :reload

If you make some changes to the source code and want GHCi to recompile
208
the program, give the :ghci-cmd:`:reload` command. The program will be
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
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
compilation setting (see :ref:`recomp`).

.. _ghci-compiled:

Loading compiled code
---------------------

.. index::
   single: compiled code; in GHCi

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 copy of the ``base``
package, which contains the ``Prelude``.

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.

234
When loading up source modules with :ghci-cmd:`:load`, GHCi normally looks for
235 236 237 238 239
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`` and ``C``:

240
.. code-block:: none
241 242 243 244 245 246 247 248 249

          A
         / \
        B   C
         \ /
          D

We can compile ``D``, then load the whole program, like this:

250
.. code-block:: none
251 252 253 254 255 256

    Prelude> :! ghc -c -dynamic D.hs
    Prelude> :load A
    Compiling B                ( B.hs, interpreted )
    Compiling C                ( C.hs, interpreted )
    Compiling A                ( A.hs, interpreted )
257
    Ok, modules loaded: A, B, C, D (D.o).
258 259 260 261 262 263 264
    *Main>

In the messages from the compiler, we see that there is no line for
``D``. This is because it isn't necessary to compile ``D``, because the
source and everything it depends on is unchanged since the last
compilation.

265
Note the :ghc-flag:`-dynamic` flag to GHC: GHCi uses dynamically-linked object
266 267 268
code (if you are on a platform that supports it), and so in order to use
compiled code with GHCi it must be compiled for dynamic linking.

269
At any time you can use the command :ghci-cmd:`:show modules` to get a list of
270 271
the modules currently loaded into GHCi:

272
.. code-block:: none
273 274 275 276 277 278 279 280 281 282 283 284

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

If we now modify the source of ``D`` (or pretend to: using the Unix command
``touch`` 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:

285
.. code-block:: none
286 287 288 289 290 291 292 293 294 295 296 297 298 299

    *Main> :! touch D.hs
    *Main> :reload
    Compiling D                ( D.hs, interpreted )
    Ok, modules loaded: A, B, C, D.
    *Main>

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.

So let's try compiling one of the other modules:

300
.. code-block:: none
301 302 303 304 305 306 307 308 309 310 311 312 313 314

    *Main> :! ghc -c C.hs
    *Main> :load A
    Compiling D                ( D.hs, interpreted )
    Compiling B                ( B.hs, interpreted )
    Compiling C                ( C.hs, interpreted )
    Compiling A                ( A.hs, interpreted )
    Ok, modules loaded: A, B, C, D.

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

315
.. code-block:: none
316 317 318 319 320 321

    *Main> :! ghc -c D.hs
    *Main> :reload
    Ok, modules loaded: A, B, C, D.

Nothing happened! Here's another lesson: newly compiled modules aren't
322
picked up by :ghci-cmd:`:reload`, only :ghci-cmd:`:load`:
323

324
.. code-block:: none
325 326 327 328

    *Main> :load A
    Compiling B                ( B.hs, interpreted )
    Compiling A                ( A.hs, interpreted )
329
    Ok, modules loaded: A, B, C (C.o), D (D.o).
330 331 332 333 334 335 336

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 :ref:`ghci-scope`). For this reason, you might
sometimes want to force GHCi to load a module using the interpreter.
This can be done by prefixing a ``*`` to the module name or filename
337
when using :ghci-cmd:`:load`, for example
338

339
.. code-block:: none
340 341 342 343 344 345 346 347 348 349 350 351 352 353

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

When the ``*`` 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 ``:add *M`` to specify that you
want ``M`` to be interpreted (note that this might cause other modules
to be interpreted too, because compiled modules cannot depend on
interpreted ones).

To always compile everything to object code and never use the
354
interpreter, use the :ghc-flag:`-fobject-code` option (see :ref:`ghci-obj`).
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

.. hint::
    Since GHCi will only use a compiled object file if it can be sure
    that the compiled version is up-to-date, a good technique when working
    on a large program is to occasionally run ``ghc --make`` to compile the
    whole project (say before you go for lunch :-), then continue working in
    the interpreter. As you modify code, the changed modules will be
    interpreted, but the rest of the project will remain compiled.

.. _interactive-evaluation:

Interactive evaluation at the prompt
------------------------------------

When you type an expression at the prompt, GHCi immediately evaluates
and prints the result:

372
.. code-block:: none
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387

    Prelude> reverse "hello"
    "olleh"
    Prelude> 5+5
    10

.. _actions-at-prompt:

I/O actions at the prompt
~~~~~~~~~~~~~~~~~~~~~~~~~

GHCi does more than simple expression evaluation at the prompt. If you
enter an expression of type ``IO a`` for some ``a``, then GHCi
*executes* it as an IO-computation.

388
.. code-block:: none
389 390 391 392 393 394 395 396 397

    Prelude> "hello"
    "hello"
    Prelude> putStrLn "hello"
    hello

This works even if the type of the expression is more general, provided
it can be *instantiated* to ``IO a``. For example

398
.. code-block:: none
399 400 401 402 403 404 405 406 407 408 409 410 411

    Prelude> return True
    True

Furthermore, GHCi will print the result of the I/O action if (and only
if):

-  The result type is an instance of ``Show``.

-  The result type is not ``()``.

For example, remembering that ``putStrLn :: String -> IO ()``:

412
.. code-block:: none
413 414 415 416 417 418 419 420 421

    Prelude> putStrLn "hello"
    hello
    Prelude> do { putStrLn "hello"; return "yes" }
    hello
    "yes"

.. _ghci-stmts:

Ben Gamari's avatar
Ben Gamari committed
422
Using ``do`` notation at the prompt
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. index::
   single: do-notation; in GHCi
   single: statements; in GHCi

GHCi actually accepts statements 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.

The syntax of a statement accepted at the GHCi prompt is exactly the
same as the syntax of a statement in a Haskell ``do`` expression.
However, there's no monad overloading here: statements typed at the
prompt must be in the ``IO`` monad.

438
.. code-block:: none
439 440 441 442 443 444 445 446 447 448

    Prelude> x <- return 42
    Prelude> print x
    42
    Prelude>

The statement ``x <- return 42`` means “execute ``return 42`` in the
``IO`` monad, and bind the result to ``x``\ ”. We can then use ``x`` in
future statements, for example to print it as we did above.

449
.. ghc-flag:: -fprint-bind-result
450 451 452 453
    :shortdesc: :ref:`Turn on printing of binding results in GHCi <ghci-stmts>`
    :type: dynamic
    :reverse: -fno-print-bind-result
    :category:
454

455 456
    If :ghc-flag:`-fprint-bind-result` is set then GHCi will print the result of a
    statement if and only if:
457

458 459
    - The statement is not a binding, or it is a monadic binding
      (``p <- e``) that binds exactly one variable.
460

461 462
    - The variable's type is not polymorphic, is not ``()``, and is an
      instance of ``Show``.
463 464 465 466

Of course, you can also bind normal non-IO expressions using the
``let``\-statement:

467
.. code-block:: none
468 469 470 471 472 473 474 475 476 477

    Prelude> let x = 42
    Prelude> x
    42
    Prelude>

Another important difference between the two types of binding is that
the monadic bind (``p <- e``) is *strict* (it evaluates ``e``), whereas
with the ``let`` form, the expression isn't evaluated immediately:

478
.. code-block:: none
479 480 481 482 483 484 485 486 487

    Prelude> let x = error "help!"
    Prelude> print x
    *** Exception: help!
    Prelude>

Note that ``let`` bindings do not automatically print the value bound,
unlike monadic bindings.

roshats's avatar
roshats committed
488
You can also define functions at the prompt:
489

490
.. code-block:: none
491

roshats's avatar
roshats committed
492
    Prelude> add a b = a + b
493 494 495 496 497 498 499 500 501
    Prelude> add 1 2
    3
    Prelude>

However, this quickly gets tedious when defining functions with multiple
clauses, or groups of mutually recursive functions, because the complete
definition has to be given on a single line, using explicit semicolons
instead of layout:

502
.. code-block:: none
503

roshats's avatar
roshats committed
504
    Prelude> f op n [] = n ; f op n (h:t) = h `op` f op n t
505 506 507 508
    Prelude> f (+) 0 [1..3]
    6
    Prelude>

Ben Gamari's avatar
Ben Gamari committed
509 510 511 512 513
.. ghci-cmd:: :{
              :}

    Begin or end a multi-line GHCi command block.

514 515 516 517
To alleviate this issue, GHCi commands can be split over multiple lines,
by wrapping them in ``:{`` and ``:}`` (each on a single line of its
own):

518
.. code-block:: none
519 520

    Prelude> :{
roshats's avatar
roshats committed
521 522
    Prelude| g op n [] = n
    Prelude| g op n (h:t) = h `op` g op n t
523 524 525 526 527 528 529 530 531 532 533
    Prelude| :}
    Prelude> g (*) 1 [1..3]
    6

Such multiline commands can be used with any GHCi command, and note that
the layout rule is in effect. The main purpose of multiline commands is
not to replace module loading but to make definitions in .ghci-files
(see :ref:`ghci-dot-files`) more readable and maintainable.

Any exceptions raised during the evaluation or execution of the
statement are caught and printed by the GHCi command line interface (for
534 535
more information on exceptions, see the module :base-ref:`Control.Exception.` in
the libraries documentation.
536 537 538 539 540 541

Every new binding shadows any existing bindings of the same name,
including entities that are in scope in the current module context.

.. warning::
    Temporary bindings introduced at the prompt only last until the
542 543 544
    next :ghci-cmd:`:load` or :ghci-cmd:`:reload` command, at which time they
    will be simply lost. However, they do survive a change of context with
    :ghci-cmd:`:module`: the temporary bindings just move to the new location.
545 546 547

.. hint::
    To get a list of the bindings currently in scope, use the
548
    :ghci-cmd:`:show bindings` command:
549

550
    .. code-block:: none
551 552 553 554 555 556 557 558 559

        Prelude> :show bindings
        x :: Int
        Prelude>

.. hint::
    If you turn on the ``+t`` option, GHCi will show the type of each
    variable bound by a statement. For example:

560
    .. code-block:: none
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581

        Prelude> :set +t
        Prelude> let (x:xs) = [1..]
        x :: Integer
        xs :: [Integer]

    .. index::
        single: +t option; in GHCi


.. _ghci-multiline:

Multiline input
~~~~~~~~~~~~~~~

Apart from the ``:{ ... :}`` syntax for multi-line input mentioned
above, GHCi also has a multiline mode, enabled by ``:set +m``,
``:set +m`` 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:

582
.. code-block:: none
583 584 585 586 587 588 589 590 591 592

    Prelude> :set +m
    Prelude> let x = 42
    Prelude|

Further bindings can be added to this ``let`` 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
``let`` we have to line them up:

593
.. code-block:: none
594 595 596 597 598 599 600 601 602

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

Explicit braces and semicolons can be used instead of layout:

603
.. code-block:: none
604 605 606 607 608 609 610 611 612 613 614 615 616 617

    Prelude> do {
    Prelude| putStrLn "hello"
    Prelude| ;putStrLn "world"
    Prelude| }
    hello
    world
    Prelude>

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

Multiline mode is useful when entering monadic ``do`` statements:

618
.. code-block:: none
619 620 621 622 623 624 625 626 627 628 629 630 631 632

    Control.Monad.State> flip evalStateT 0 $ do
    Control.Monad.State| i <- 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>

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

633
.. code-block:: none
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648

    Prelude> do
    Prelude| putStrLn "Hello, World!"
    Prelude| ^C
    Prelude>

.. _ghci-decls:

Type, class and other declarations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

At the GHCi prompt you can also enter any top-level Haskell declaration,
including ``data``, ``type``, ``newtype``, ``class``, ``instance``,
``deriving``, and ``foreign`` declarations. For example:

649
.. code-block:: none
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669

    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 <interactive>:2:6
    instance Enum T -- Defined at <interactive>:2:45
    instance Eq T -- Defined at <interactive>:2:30
    instance Ord T -- Defined at <interactive>:2:34
    instance Show T -- Defined at <interactive>:2:39

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:

670
.. code-block:: none
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

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

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

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

689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
Class and type-family instance declarations are simply added to the
list of available instances, with one exception. Since you might want
to re-define one, a class instance *replaces* any earlier instance
with an identical head. You aren't allowed to re-define a type family
instance, since it might not be type safe to do so. Instead, re-define
the whole type-family. (See :ref:`type-families`.) For example:

.. code-block:: none

    Prelude> type family T a b
    Prelude> type instance T a b = a
    Prelude> let uc :: a -> T a b; uc = id

    Prelude> type instance T a b = b

    <interactive>:3:15: error:
        Conflicting family instance declarations:
          T a b = a -- Defined at <interactive>:3:15
          T a b = b -- Defined at <interactive>:5:15

    -- Darn! We have to re-declare T.

    Prelude> type family T a b
    -- This is a brand-new T, unrelated to the old one
    Prelude> type instance T a b = b
    Prelude> uc 'a' :: Int

    <interactive>:8:1: error:
        • Couldn't match type ‘Char’ with ‘Int’
          Expected type: Int
            Actual type: Ghci1.T Char b0
        • In the expression: uc 'a' :: Int
          In an equation for ‘it’: it = uc 'a' :: Int
722 723 724 725 726 727 728 729 730 731

.. _ghci-scope:

What's really in scope at the prompt?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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:

732
-  The :ghci-cmd:`:load`, :ghci-cmd:`:add`, and :ghci-cmd:`:reload` commands
733 734 735 736
   (:ref:`ghci-load-scope`).

-  The ``import`` declaration (:ref:`ghci-import-decl`).

737
-  The :ghci-cmd:`:module` command (:ref:`ghci-module-cmd`).
738

739
The command :ghci-cmd:`:show imports` will show a summary of which modules
740 741 742 743 744
contribute to the top-level scope.

.. hint::
    GHCi will tab-complete names that are in scope; for example, if
    you run GHCi and type ``J<tab>`` then GHCi will expand it to
745
    ``Just``.
746 747 748 749 750 751

.. _ghci-load-scope:

The effect of ``:load`` on what is in scope
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

752
The :ghci-cmd:`:load`, :ghci-cmd:`:add`, and :ghci-cmd:`:reload` commands
753 754 755 756
(:ref:`loading-source-files` and :ref:`ghci-compiled`) affect the
top-level scope. Let's start with the simple cases; when you start GHCi
the prompt looks like this:

757
.. code-block:: none
758 759 760 761 762 763 764 765 766

    Prelude>

which indicates that everything from the module ``Prelude`` is currently
in scope; the visible identifiers are exactly those that would be
visible in a Haskell source file with no ``import`` declarations.

If we now load a file into GHCi, the prompt will change:

767
.. code-block:: none
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790

    Prelude> :load Main.hs
    Compiling Main             ( Main.hs, interpreted )
    *Main>

The new prompt is ``*Main``, which indicates that we are typing
expressions in the context of the top-level of the ``Main`` module.
Everything that is in scope at the top-level in the module ``Main`` we
just loaded is also in scope at the prompt (probably including
``Prelude``, as long as ``Main`` doesn't explicitly hide it).

The syntax in the prompt ``*module`` indicates that it is the full
top-level scope of ⟨module⟩ that is contributing to the scope for
expressions typed at the prompt. Without the ``*``, just the exports of
the module are visible.

.. note::
    For technical reasons, GHCi can only support the ``*``-form for
    modules that are interpreted. Compiled modules and package modules can
    only contribute their exports to the current scope. To ensure that GHCi
    loads the interpreted version of a module, add the ``*`` when loading
    the module, e.g. ``:load *M``.

791
In general, after a :ghci-cmd:`:load` command, an automatic import is added to
792 793 794 795 796 797
the scope for the most recently loaded "target" module, in a ``*``-form
if possible. For example, if you say ``:load foo.hs bar.hs`` and
``bar.hs`` contains module ``Bar``, then the scope will be set to
``*Bar`` if ``Bar`` is interpreted, or if ``Bar`` is compiled it will be
set to ``Prelude Bar`` (GHCi automatically adds ``Prelude`` if it isn't
present and there aren't any ``*``-form modules). These
798
automatically-added imports can be seen with :ghci-cmd:`:show imports`:
799

800
.. code-block:: none
801 802 803 804 805 806 807 808 809

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

and the automatically-added import is replaced the next time you use
810 811
:ghci-cmd:`:load`, :ghci-cmd:`:add`, or :ghci-cmd:`:reload`. It can also be
removed by :ghci-cmd:`:module` as with normal imports.
812 813 814 815 816 817 818 819 820 821 822 823 824

.. _ghci-import-decl:

Controlling what is in scope with ``import``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

We are not limited to a single module: GHCi can combine scopes from
multiple modules, in any mixture of ``*`` and non-\ ``*`` forms. GHCi
combines the scopes from all of these modules to form the scope that is
in effect at the prompt.

To add modules to the scope, use ordinary Haskell ``import`` syntax:

825
.. code-block:: none
826 827 828 829 830 831 832 833 834

    Prelude> import System.IO
    Prelude System.IO> hPutStrLn stdout "hello\n"
    hello
    Prelude System.IO>

The full Haskell import syntax is supported, including ``hiding`` and
``as`` clauses. The prompt shows the modules that are currently
imported, but it omits details about ``hiding``, ``as``, and so on. To
835
see the full story, use :ghci-cmd:`:show imports`:
836

837
.. code-block:: none
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860

    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>

Note that the ``Prelude`` import is marked as implicit. It can be
overridden with an explicit ``Prelude`` import, just like in a Haskell
module.

With multiple modules in scope, especially multiple ``*``-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.

.. _ghci-module-cmd:

Controlling what is in scope with the ``:module`` command
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

861 862
Another way to manipulate the scope is to use the :ghci-cmd:`:module`
command, whose syntax is this:
863

864
.. code-block:: none
865 866 867 868 869 870 871 872 873

    :module +|- *mod1 ... *modn

Using the ``+`` form of the ``module`` commands adds modules to the
current scope, and ``-`` removes them. Without either ``+`` or ``-``,
the current scope is replaced by the set of modules specified. Note that
if you use this form and leave out ``Prelude``, an implicit ``Prelude``
import will be added automatically.

874
The :ghci-cmd:`:module` command provides a way to do two things that cannot be
875 876
done with ordinary ``import`` declarations:

877
-  :ghci-cmd:`:module` supports the ``*`` modifier on modules, which opens the
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
   full top-level scope of a module, rather than just its exports.

-  Imports can be *removed* from the context, using the syntax
   ``:module -M``. The ``import`` syntax is cumulative (as in a Haskell
   module), so this is the only way to subtract from the scope.

.. _ghci-import-qualified:

Qualified names
^^^^^^^^^^^^^^^

To make life slightly easier, the GHCi prompt also behaves as if there
is an implicit ``import qualified`` declaration for every module in
every package, and every module currently loaded into GHCi. This
behaviour can be disabled with the ``-fno-implicit-import-qualified`` flag.

.. index::
   single: -fno-implicit-import-qualified

``:module`` and ``:load``
^^^^^^^^^^^^^^^^^^^^^^^^^

900 901 902
It might seem that :ghci-cmd:`:module`/``import`` and
:ghci-cmd:`:load`/:ghci-cmd:`:add`/:ghci-cmd:`:reload` do similar things: you
can use both to bring a module into scope. However, there is a very important
903 904 905
difference. GHCi is concerned with two sets of modules:

-  The set of modules that are currently *loaded*. This set is modified
906 907
   by :ghci-cmd:`:load`, :ghci-cmd:`:add` and :ghci-cmd:`:reload`, and can be shown with
   :ghci-cmd:`:show modules`.
908

909 910 911 912 913
-  The set of modules that are currently *in scope* at the prompt. This set is
   modified by ``import`` and :ghci-cmd:`:module`, and it is also modified
   automatically after :ghci-cmd:`:load`, :ghci-cmd:`:add`, and
   :ghci-cmd:`:reload`, as described above. The set of modules in scope can be
   shown with :ghci-cmd:`:show imports`.
914

915
You can add a module to the scope (via :ghci-cmd:`:module` or ``import``) only
916
if either (a) it is loaded, or (b) it is a module from a package that
917
GHCi knows about. Using :ghci-cmd:`:module` or ``import`` to try bring into
918
scope a non-loaded module may result in the message
919
``module M is not loaded``.
920 921 922 923 924 925 926 927 928

The ``:main`` and ``:run`` commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

929
Instead, we can use the :ghci-cmd:`:main` command. This runs whatever ``main``
930 931 932
is in scope, with any arguments being treated the same as command-line
arguments, e.g.:

933
.. code-block:: none
934

roshats's avatar
roshats committed
935
    Prelude> main = System.Environment.getArgs >>= print
936 937 938 939 940 941 942
    Prelude> :main foo bar
    ["foo","bar"]

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:

943
.. code-block:: none
944 945 946 947 948 949 950

    Prelude> :main foo "bar baz"
    ["foo","bar baz"]
    Prelude> :main ["foo", "bar baz"]
    ["foo","bar baz"]

Finally, other functions can be called, either with the ``-main-is``
951
flag or the :ghci-cmd:`:run` command:
952

953
.. code-block:: none
954

roshats's avatar
roshats committed
955 956
    Prelude> foo = putStrLn "foo" >> System.Environment.getArgs >>= print
    Prelude> bar = putStrLn "bar" >> System.Environment.getArgs >>= print
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
    Prelude> :set -main-is foo
    Prelude> :main foo "bar baz"
    foo
    ["foo","bar baz"]
    Prelude> :run bar ["foo", "bar baz"]
    bar
    ["foo","bar baz"]

The ``it`` variable
~~~~~~~~~~~~~~~~~~~

.. index::
   single: it variable

Whenever an expression (or a non-binding statement, to be precise) is
typed at the prompt, GHCi implicitly binds its value to the variable
``it``. For example:

975
.. code-block:: none
976 977 978 979 980 981 982 983 984 985

    Prelude> 1+2
    3
    Prelude> it * 2
    6

What actually happens is that GHCi typechecks the expression, and if it
doesn't have an ``IO`` type, then it transforms it as follows: an
expression ``e`` turns into

986
.. code-block:: none
987 988 989 990 991 992 993 994 995

    let it = e;
    print it

which is then run as an IO-action.

Hence, the original expression must have a type which is an instance of
the ``Show`` class, or GHCi will complain:

996
.. code-block:: none
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013

    Prelude> id

    <interactive>:1:0:
        No instance for (Show (a -> a))
          arising from use of `print' at <interactive>:1:0-1
        Possible fix: add an instance declaration for (Show (a -> a))
        In the expression: print it
        In a 'do' expression: print it

The error message contains some clues as to the transformation happening
internally.

If the expression was instead of type ``IO a`` for some ``a``, then
``it`` will be bound to the result of the ``IO`` computation, which is
of type ``a``. eg.:

1014
.. code-block:: none
1015

1016 1017
    Prelude> Data.Time.getZonedTime
    2017-04-10 12:34:56.93213581 UTC
1018
    Prelude> print it
1019
    2017-04-10 12:34:56.93213581 UTC
1020 1021 1022

The corresponding translation for an IO-typed ``e`` is

1023
.. code-block:: none
1024 1025 1026 1027 1028 1029

    it <- e

Note that ``it`` is shadowed by the new value each time you evaluate a
new expression, and the old value of ``it`` is lost.

Matthew Pickering's avatar
Matthew Pickering committed
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
In order to stop the value ``it`` being bound on each command, the flag
:ghc-flag:`-fno-it` can be set. The ``it`` variable can be the source
of space leaks due to how shadowed declarations are handled by
GHCi (see :ref:`ghci-decls`).

.. ghc-flag:: -fno-it
    :shortdesc: No longer set the special variable ``it``.
    :type: dynamic
    :reverse: -fno-no-it
    :category:

    When this flag is set, the variable ``it`` will no longer be set
    to the result of the previously evaluated expression.

1044 1045 1046 1047 1048 1049 1050 1051 1052
.. _extended-default-rules:

Type defaulting in GHCi
~~~~~~~~~~~~~~~~~~~~~~~

.. index::
   single: Type defaulting; in GHCi
   single: Show class

1053 1054
.. extension:: ExtendedDefaultRules
    :shortdesc: Use GHCi's extended default rules in a normal module.
1055 1056

    :since: 6.8.1
1057 1058 1059

    Allow defaulting to take place for more than just numeric classes.

1060 1061
Consider this GHCi session:

1062
.. code-block:: none
1063 1064 1065 1066 1067 1068 1069 1070

      ghci> reverse []

What should GHCi do? Strictly speaking, the program is ambiguous.
``show (reverse [])`` (which is what GHCi computes here) has type
``Show a => String`` and how that displays depends on the type ``a``.
For example:

1071
.. code-block:: none
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089

      ghci> reverse ([] :: String)
      ""
      ghci> reverse ([] :: [Int])
      []

However, it is tiresome for the user to have to specify the type, so
GHCi extends Haskell's type-defaulting rules (Section 4.3.4 of the
Haskell 2010 Report) as follows. The standard rules take each group of
constraints ``(C1 a, C2 a, ..., Cn a)`` for each type variable ``a``,
and defaults the type variable if

1. The type variable ``a`` appears in no other constraints

2. All the classes ``Ci`` are standard.

3. At least one of the classes ``Ci`` is numeric.

1090
At the GHCi prompt, or with GHC if the :extension:`ExtendedDefaultRules` flag
1091
is given, the types are instead resolved with the following method:
1092

1093
Find all the unsolved constraints. Then:
1094

1095 1096 1097 1098 1099 1100 1101 1102 1103
-  Find those that are of form ``(C a)`` where ``a`` is a type variable, and
   partition those constraints into groups that share a common type variable ``a``.

-  Keep only the groups in which at least one of the classes is an
   **interactive class** (defined below).

-  Now, for each remaining group G, try each type ``ty`` from the default-type list
   in turn; if setting ``a = ty`` would allow the constraints in G to be completely
   solved. If so, default ``a`` to ``ty``.
1104

1105 1106
-  The unit type ``()`` and the list type ``[]`` are added to the start of
   the standard list of types which are tried when doing type defaulting.
1107

1108 1109 1110 1111
Note that any multi-parameter constraints ``(D a b)`` or ``(D [a] Int)`` do not
participate in the process (either to help or to hinder); but they must of course
be soluble once the defaulting process is complete.

1112
The last point means that, for example, this program: ::
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136

    main :: IO ()
    main = print def

    instance Num ()

    def :: (Num a, Enum a) => a
    def = toEnum 0

prints ``()`` rather than ``0`` as the type is defaulted to ``()``
rather than ``Integer``.

The motivation for the change is that it means ``IO a`` actions default
to ``IO ()``, which in turn means that ghci won't try to print a result
when running them. This is particularly important for ``printf``, which
has an instance that returns ``IO a``. However, it is only able to
return ``undefined`` (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 ``Integer`` then ghci gives an error when running a
printf.

See also :ref:`actions-at-prompt` for how the monad of a computational
expression defaults to ``IO`` if possible.

1137 1138 1139 1140 1141 1142
Interactive classes
^^^^^^^^^^^^^^^^^^^

.. index::
   single: Interactive classes

1143
The interactive classes (only relevant when :extension:`ExtendedDefaultRules`
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
is in effect) are: any numeric class, ``Show``, ``Eq``, ``Ord``,
``Foldable`` or ``Traversable``.

As long as a type variable is constrained by one of these classes, defaulting
will occur, as outlined above.

Extended rules around ``default`` declarations
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. index::
   single: default declarations

Since the rules for defaulting are relaxed under
1157
:extension:`ExtendedDefaultRules`, the rules for ``default`` declarations
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
are also relaxed. According to Section 4.3.4 of the Haskell 2010 Report,
a ``default`` declaration looks like ``default (t1, ..., tn)`` where, for
each ``ti``, ``Num ti`` must hold. This is relaxed to say that for each
``ti``, there must exist an interactive class ``C`` such that ``C ti`` holds.
This means that type *constructors* can be allowed in these lists.
For example, the following works if you wish your ``Foldable`` constraints
to default to ``Maybe`` but your ``Num`` constraints to still default
to ``Integer`` or ``Double``: ::

    default (Maybe, Integer, Double)

1169 1170 1171 1172 1173 1174 1175 1176
.. _ghci-interactive-print:

Using a custom interactive printing function
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. index::
   single: Custom printing function; in GHCi

1177 1178 1179
Since GHC 7.6.1, GHCi prints the result of expressions typed at the prompt
using the function ``System.IO.print``. Its type signature is ``Show a => a ->
IO ()``, and it works by converting the value to ``String`` using ``show``.
1180 1181 1182 1183

This is not ideal in certain cases, like when the output is long, or
contains strings with non-ascii characters.

1184
The :ghc-flag:`-interactive-print ⟨name⟩` flag allows to specify any function
1185 1186 1187 1188
of type ``C a => a -> IO ()``, for some constraint ``C``, as the function for
printing evaluated expressions. The function can reside in any loaded module or
any registered package, but only when it resides in a registered package will
it survive a :ghci-cmd:`:cd`, :ghci-cmd:`:add`, :ghci-cmd:`:load`,
1189
:ghci-cmd:`:reload` or, :ghci-cmd:`:set`.
1190

1191
.. ghc-flag:: -interactive-print ⟨name⟩
1192 1193 1194 1195
    :shortdesc: :ref:`Select the function to use for printing evaluated
        expressions in GHCi <ghci-interactive-print>`
    :type: dynamic
    :category:
1196

1197
    Set the function used by GHCi to print evaluation results. Given name
1198 1199
    must be of type ``C a => a -> IO ()``.

1200
As an example, suppose we have following special printing module: ::
1201

1202 1203
    module SpecPrinter where
    import System.IO
1204

1205
    sprint a = putStrLn $ show a ++ "!"
1206 1207 1208 1209

The ``sprint`` function adds an exclamation mark at the end of any
printed value. Running GHCi with the command:

1210
.. code-block:: none
1211

1212
    ghci -interactive-print=SpecPrinter.sprint SpecPrinter
1213 1214 1215 1216

will start an interactive session where values with be printed using
``sprint``:

1217
.. code-block:: none
1218

1219 1220 1221 1222
    *SpecPrinter> [1,2,3]
    [1,2,3]!
    *SpecPrinter> 42
    42!
1223 1224 1225 1226

A custom pretty printing function can be used, for example, to format
tree-like and nested structures in a more readable way.

1227
The :ghc-flag:`-interactive-print ⟨name⟩` flag can also be used when running
1228
GHC in ``-e mode``:
1229

1230
.. code-block:: none
1231

1232 1233
    % ghc -e "[1,2,3]" -interactive-print=SpecPrinter.sprint SpecPrinter
    [1,2,3]!
1234

Simon Marlow's avatar
Simon Marlow committed
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
.. _ghci-stack-traces:

Stack Traces in GHCi
~~~~~~~~~~~~~~~~~~~~

.. index::
  simple: stack trace; in GHCi

[ This is an experimental feature enabled by the new
``-fexternal-interpreter`` flag that was introduced in GHC 8.0.1.  It
is currently not supported on Windows.]

GHCi can use the profiling system to collect stack trace information
when running interpreted code.  To gain access to stack traces, start
GHCi like this:

.. code-block:: none

    ghci -fexternal-interpreter -prof

This runs the interpreted code in a separate process (see
:ref:`external-interpreter`) and runs it in profiling mode to collect
call stack information.  Note that because we're running the
interpreted code in profiling mode, all packages that you use must be
compiled for profiling.  The ``-prof`` flag to GHCi only works in
conjunction with ``-fexternal-interpreter``.

There are three ways to get access to the current call stack.

- ``error`` and ``undefined`` automatically attach the current stack
1265 1266
  to the error message.  This often complements the ``HasCallStack``
  stack (see :ref:`hascallstack`), so both call stacks are
Simon Marlow's avatar
Simon Marlow committed
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
  shown.

- ``Debug.Trace.traceStack`` is a version of ``Debug.Trace.trace``
  that also prints the current call stack.

- Functions in the module ``GHC.Stack`` can be used to get the current
  stack and render it.

You don't need to use ``-fprof-auto`` for interpreted modules,
annotations are automatically added at a granularity fine enough to
distinguish individual call sites.  However, you won't see any call
stack information for compiled code unless it was compiled with
``-fprof-auto`` or has explicit ``SCC`` annotations (see
:ref:`scc-pragma`).

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 1326 1327 1328 1329 1330
.. _ghci-debugger:

The GHCi Debugger
-----------------

.. index::
   single: debugger; in GHCi

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
interpreted modules; compiled code is invisible to the debugger [5]_.

The debugger provides the following:

-  The ability to set a breakpoint 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.

-  Execution can be single-stepped: 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.

-  Execution can take place in tracing mode, 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.

-  Exceptions (e.g. pattern matching failure and ``error``) can be
   treated as breakpoints, to help locate the source of an exception in
   the program.

There is currently no support for obtaining a “stack trace”, 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
:ref:`ghci-debugger-exceptions`).

.. _breakpoints:

Breakpoints and inspecting variables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1331
Let's use quicksort as a running example. Here's the code: ::
1332 1333 1334 1335 1336 1337 1338 1339 1340

    qsort [] = []
    qsort (a:as) = qsort left ++ [a] ++ qsort right
      where (left,right) = (filter (<=a) as, filter (>a) as)

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

First, load the module into GHCi:

1341
.. code-block:: none
1342 1343 1344 1345 1346 1347 1348 1349 1350

    Prelude> :l qsort.hs
    [1 of 1] Compiling Main             ( qsort.hs, interpreted )
    Ok, modules loaded: Main.
    *Main>

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

1351
.. code-block:: none
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364

    *Main> :break 2
    Breakpoint 0 activated at qsort.hs:2:15-46
    *Main>

The command ``:break 2`` sets a breakpoint on line 2 of the most
recently-loaded module, in this case ``qsort.hs``. Specifically, it
picks the leftmost complete subexpression on that line on which to set
the breakpoint, which in this case is the expression
``(qsort left ++ [a] ++ qsort right)``.

Now, we run the program:

1365
.. code-block:: none
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377

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

Execution has stopped at the breakpoint. The prompt has changed to
indicate that we are currently stopped at a breakpoint, and the
location: ``[qsort.hs:2:15-46]``. To further clarify the location, we
1378
can use the :ghci-cmd:`:list` command:
1379

1380
.. code-block:: none
1381 1382 1383 1384 1385 1386

    [qsort.hs:2:15-46] *Main> :list
    1  qsort [] = []
    2  qsort (a:as) = qsort left ++ [a] ++ qsort right
    3    where (left,right) = (filter (<=a) as, filter (>a) as)

1387
The :ghci-cmd:`:list` command lists the source code around the current
1388 1389 1390 1391 1392 1393 1394 1395
breakpoint. If your output device supports it, then GHCi will highlight
the active subexpression in bold.

GHCi has provided bindings for the free variables [6]_ of the expression
on which the breakpoint was placed (``a``, ``left``, ``right``), and
additionally a binding for the result of the expression (``_result``).
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
1396
can ask for their types with :ghci-cmd:`:type`, and so on. There is one
1397 1398 1399
important difference though: these variables may only have partial
types. For example, if we try to display the value of ``left``:

1400
.. code-block:: none
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416

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

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

This is because ``qsort`` 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 ``left`` at the prompt, GHCi can't figure out which
instance of ``Show`` to use, so it emits the type error above.

Fortunately, the debugger includes a generic printing command,
1417
:ghci-cmd:`:print`, which can inspect the actual runtime value of a variable and
1418 1419
attempt to reconstruct its type. If we try it on ``left``:

1420
.. code-block:: none
1421 1422 1423 1424 1425 1426 1427

    [qsort.hs:2:15-46] *Main> :set -fprint-evld-with-show
    [qsort.hs:2:15-46] *Main> :print left
    left = (_t1::[a])

This isn't particularly enlightening. What happened is that ``left`` is
bound to an unevaluated computation (a suspension, or thunk), and
1428 1429 1430 1431 1432 1433 1434 1435 1436
:ghci-cmd:`:print` does not force any evaluation. The idea is that
:ghci-cmd:`:print` 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 :ref:`nested-breakpoints`). Rather than forcing thunks,
:ghci-cmd:`:print` binds each thunk to a fresh variable beginning with an
underscore, in this case ``_t1``.

Ben Gamari's avatar
Ben Gamari committed
1437 1438 1439 1440 1441 1442 1443 1444
.. ghc-flag:: -fprint-evld-with-show
    :shortdesc: Instruct :ghci-cmd:`:print` to use ``Show`` instances where possible.
    :category: interactive
    :type: dynamic

    The flag :ghc-flag:`-fprint-evld-with-show` instructs :ghci-cmd:`:print` to reuse
    available ``Show`` instances when possible. This happens only when the
    contents of the variable being inspected are completely evaluated.
1445

1446 1447 1448 1449
If we aren't concerned about preserving the evaluatedness of a variable, we can
use :ghci-cmd:`:force` instead of :ghci-cmd:`:print`. The :ghci-cmd:`:force`
command behaves exactly like :ghci-cmd:`:print`, except that it forces the
evaluation of any thunks it encounters:
1450

1451
.. code-block:: none
1452 1453 1454 1455

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

1456
Now, since :ghci-cmd:`:force` has inspected the runtime value of ``left``, it
1457 1458 1459
has reconstructed its type. We can see the results of this type
reconstruction:

1460
.. code-block:: none
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472

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

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

1473
.. code-block:: none
1474 1475 1476 1477 1478 1479

    [qsort.hs:2:15-46] *Main> a
    8

You might find it useful to use Haskell's ``seq`` function to evaluate
individual thunks rather than evaluating the whole expression with
1480
:ghci-cmd:`:force`. For example:
1481

1482
.. code-block:: none
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492

    [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])

We evaluated only the ``_t1`` thunk, revealing the head of the list, and
the tail is another thunk now bound to ``_t2``. The ``seq`` function is
1493
a little inconvenient to use here, so you might want to use :ghci-cmd:`:def` to
1494 1495 1496 1497
make a nicer interface (left as an exercise for the reader!).

Finally, we can continue the current execution:

1498
.. code-block:: none
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518

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

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

.. _setting-breakpoints:

Setting breakpoints
^^^^^^^^^^^^^^^^^^^

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

1519
.. code-block:: none
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529

       :break identifier

Where ⟨identifier⟩ 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.

Breakpoints can also be set by line (and optionally column) number:

1530
.. code-block:: none
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549

       :break line
       :break line column
       :break module line
       :break module line column

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.

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
1550
altogether (see :ghc-flag:`-Wtabs` in :ref:`options-sanity`).
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563

If the module is omitted, then the most recently-loaded module is used.

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.

1564 1565
Managing breakpoints
^^^^^^^^^^^^^^^^^^^^
1566

1567
The list of breakpoints currently defined can be displayed using
1568
:ghci-cmd:`:show breaks`:
1569

1570
.. code-block:: none