GHC/GHCi

From HaskellWiki
< GHC
Jump to: navigation, search


Introduction

GHCi is GHC's interactive environment, in which Haskell expressions can be interactively evaluated and programs can be interpreted. Before reading this, read the GHCi section of the GHC User's Guide.

This page is a place to collect advice and snippets for use with the latest version of GHCi, beyond what the User's Guide covers. Please add to it!

Invoking GHCi

GHCi can be run in a number of ways, depending on your setup and requirements:

  1. standalone: ghci
  2. within the stack global project: stack repl
  3. within a specific stack project: cd project; stack repl
  4. within a specific stack project, but including GHC_PACKAGE_PATH: cd project; stack exec ghci
  5. within a temporary "fake" cabal project: cabal new-repl
  6. within a specific cabal project: cd project; cabal new-repl

Customisation

When invoked, GHCi tries to load a startup script. The documentation has the best description of where it tries to find these files. In general, the snippets on this page can be added there to enable the desired features by default. This page will assume you are using ~/.ghci, so adjust as necessary if you are using a different file.

When running GHCi from within a project, another startup script may also be specified by stack, which unfortunately can cause some of your startup script's customisations to be reset. Also, when running from cabal or stack, not all modules will be available within your startup script. Therefore, it is better to avoid using any extra modules unless you know you are running a standalone GHCi session. As such, it is recommended to use a different startup file for standalone sessions, by putting the following in your .bashrc (or equivalent for other shells):

alias ghci='ghci -v0 -ignore-dot-ghci -ghci-script ~/.ghci.standalone'

This will make GHCi load the ~/.ghci.standalone startup file instead, and there you can be free to load and use modules that you know are available in that environment. The -v0 will also ensure that GHCi is not as verbose as the default settings make it. Throughout this page, it is noted when a snippet requires modules that are not generally available in all environments.

GHCi reads its input through a library called hasekeline, which can also be customized. A typical ~/.haskeline file might look like this:

maxHistorySize: Nothing
historyDuplicates: IgnoreConsecutive
completionPromptLimit: Just 250

This will give you unlimited history, will omit history entries that are identical to the previous entry, and when using tab-completion, prompt only when the number of completions exceeds 250.

To use Vi-like keybindings (similar to Bash's set -o vi) add also the following line:

editMode: Vi

The Snippet Library

The following is the recommended basis for the .ghci file:

-- Turn off output for resource usage and types.  This is to reduce verbosity when reloading this file.
:unset +s +t
-- Turn on multi-line input and remove the distracting verbosity.
:set +m -v0
-- Turn off all compiler warnings and turn on OverloadedStrings for interactive input.
:seti -w -XOverloadedStrings
-- Set the preferred editor for use with the :e command.  I would recommend using an editor in a separate terminal, and using :r to reload, but :e can still be useful for quick edits from within GHCi.
:set editor vim

...
-- rest of file
...

-- Use :rr to reload this file.
:def! rr \_ -> return ":script ~/.ghci"
-- Turn on output of types.  This line should be last.
:set +t

Fancy Prompts

Both of the following snippets use the Haskell logo as the prompt, but this must be supported by your terminal font. Under Linux, this is probably already the case, but on Mac, this can be achieved by installing Nerd Fonts. This is easily done using brew:

brew tap caskroom/fonts
brew cask install font-hack-nerd-font

Instead, to use a lambda for the prompt, change the "\xe61f" in the snippet to "λ".

This snippet requires the directory module to configure a nice prompt:

:{
:set -package directory
dotGHCI_myPrompt promptString ms _ = do
  -- Get the current directory, replacing $HOME with a '~'.
  pwd <- getpwd
  -- Determine which is the main module.
  let main_module = head' [ m' | (m:m') <- ms, m == '*' ]
  -- Put together the final prompt string.
  -- ANSI escape sequences allow for displaying colours in compatible terminals.  See [http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html this guide] for help interpreting them.
  return $ concat [ "\STX\ESC[33m", pwd, main_module, "\ESC[37m", promptString, " \ESC[0m\STX" ]
  where
    head' (x:_) = " \ESC[38;5;227m" ++ x
    head' _     = ""
    getpwd = getpwd' <$> (System.Environment.getEnv "HOME") <*> System.Directory.getCurrentDirectory
    getpwd' home pwd = if zipWith const pwd home == home
                         then '~':drop (length home) pwd
                         else pwd
:}
:set prompt-function dotGHCI_myPrompt "\ESC[38;5;129m\xe61f"
:set prompt-cont-function dotGHCI_myPrompt "∷"

The following snippet works without loading extra modules, but requires a POSIX environment.

:{
dotGHCI_myPrompt promptString ms _ = do
  -- Get the current directory, replacing $HOME with a '~'.
  pwd <- getpwd
  -- Determine which is the main module.
  let main_module = head' [ m' | (m:m') <- ms, m == '*' ]
  -- Put together the final prompt string.
  -- ANSI escape sequences allow for displaying colours in compatible terminals.  See [http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html this guide] for help interpreting them.
  return $ concat [ "\STX\ESC[33m", pwd, main_module, "\ESC[37m", promptString, " \ESC[0m\STX" ]
  where
    head' (x:_) = " \ESC[38;5;227m" ++ x
    head' _     = ""
    getpwd = getpwd' <$> System.Environment.getEnv "HOME" <*> System.Posix.getWorkingDirectory
    getpwd' home pwd = if zipWith const pwd home == home
                         then '~':drop (length home) pwd
                         else pwd
:}
:set prompt-function dotGHCI_myPrompt "\ESC[38;5;129m\xe61f"
:set prompt-cont-function dotGHCI_myPrompt "∷"

And here's what this should look like:

~$ cd src/gitit
~/src/gitit$ ghci src/Network/Gitit.hs
~/src/gitit Network.Gititλ :info wiki
wiki :: Config -> ServerPart Response
  	-- Defined at src/Network/Gitit.hs:133:1
~/src/gitit Network.Gititλ 

Pretty Printing

GHCi's -interactive-print option allows for interactive output to be piped through a pretty printer. Here is a snippet, with custom colours:

-- Colourise ghci output (use :nopretty to disable)
-- Required libraries: pretty-show hscolour
:set -package pretty-show -package hscolour
import qualified Language.Haskell.HsColour as HSC
import qualified Language.Haskell.HsColour.Colourise as HSC
:{
dotGHCI_myPrint :: (Show a) => a -> IO ()
dotGHCI_myPrint a = putStrLn $ HSC.hscolour HSC.TTY myColourPrefs False False "" False $ Text.Show.Pretty.ppShow a
  where
    myColourPrefs = HSC.defaultColourPrefs -- { HSC.conop    = [HSC.Foreground HSC.Yellow]
                                           -- , HSC.conid    = [HSC.Foreground HSC.Yellow, HSC.Bold]
                                           -- , HSC.string   = [HSC.Foreground $ HSC.Rgb 29 193 57]
                                           -- , HSC.char     = [HSC.Foreground HSC.Cyan]
                                           -- , HSC.number   = [HSC.Foreground $ HSC.Rgb 202 170 236]
                                           -- , HSC.keyglyph = [HSC.Foreground HSC.Yellow]
                                           -- }
:}
:seti -interactive-print dotGHCI_myPrint
:def! pretty \_ -> return ":set -interactive-print dotGHCI_myPrint"
:def! nopretty \_ -> return ":set -interactive-print System.IO.print"
:m -Language.Haskell.HsColour
:m -Language.Haskell.HsColour.Colourise

The following snippet works without loading extra modules, but requires the ppsh and HsColour binaries (from pretty-show and hscolour) to be installed in your PATH.

-- Colourise ghci output (use :nopretty to disable)
:{
:def! pretty \_ -> return $ unlines [
  ":unset +t",
  "pp x = putStrLn =<< catch' (rp \"HsColour\" []) =<< catch' (rp \"ppsh\" []) (show x) where { rp = System.Process.readProcess; catch' f x = Control.Exception.catch (f x) (h x); h :: String -> Control.Exception.SomeException -> IO String; h x _ = return x }",
  ":seti -interactive-print pp",
  ":set +t"
  ]
:}
:def! nopretty \_ -> return ":set -interactive-print System.IO.print"
:pretty
:unset +t

After adding all that, you should have a slightly nicer output from GHCi:

~λ [1,2,3]
[ 1 , 2 , 3 ]
it :: Num a => [a]

Extra Commands

There are many extra utilities for GHCi. The most versatile way to access them is by invoking external binaries from definition bindings. For example, we can add an ls command by simply using the operating system's ls:

:def! ls \s -> return $ ":!ls " ++ s

And you use these definitions by simply calling them with a colon, just like the builtin GHCi commands:

~λ :ls -1adF
./
../
example.hs

HLint and Hoogle

Similarly, after installing the hoogle and hlint binaries:

:def! hoogle \s -> return $ ":!hoogle --count=25 \"" ++ s ++ "\""
:def! hlint \s -> return $ ":!hlint " ++ if null s then "." else s

This allows you to do the following from within GHCi:

~λ :hlint
No hints
~λ :hoogle is:exact Data.Set.insert
Data.Set insert :: Ord a => a -> Set a -> Set a
Data.Set.Internal insert :: Ord a => a -> Set a -> Set a
Data.SetMap insert :: (Ord k, Ord a) => k -> a -> SetMap k a -> SetMap k a
Data.Set.NonEmpty insert :: Ord a => a -> NESet a -> NESet a

Lambdabot Commands

There is an IRC bot called lambdabot which includes many tools which can be accessed directly in "offline" mode. Here are some example usages:

~λ :pl \x y -> x + 1                     -- converts code to point-free (aka pointless) form
const . (1 +)
~λ :unpl const . (1 +)                   -- converts back from point-free (aka pointless) form
(\ x _ -> 1 + x)
~λ :do getLine >>= putStrLn              -- converts binds to do notation
do { a <- getLine; putStrLn a}
~λ :undo do { a <- getLine; putStrLn a } -- converts do blocks to bind notation
getLine >>= \ a -> putStrLn a
~λ :index <<^                            -- finds the module that defines the given identifier
Control.Arrow
~λ :instances Arrow                      -- finds all instances of a given type class
(->), Kleisli m
~λ :src <<^                              -- tries to find the source code for the given identifier
a <<^ f = a <<< arr f
~λ :oeis 3 5 8 13                        -- looks up the On-Line Encyclopedia of Integer Sequences (https://oeis.org/)
https://oeis.org/A000045 Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,
...

And here's the snippet which allows for all of that:

lb s1 s2 = return $ ":!lambdabot -n -e \"" ++ s1 ++ " " ++ s2 ++ "\""
:def! lb lb ""                   -- runs arbitrary lambdabot commands
:def! pl lb "pl"                 -- converts code to point-free (aka pointless) form
:def! unpl lb "unpl"             -- converts back from point-free (aka pointless) form
:def! do lb "do"                 -- converts binds to do notation
:def! undo lb "undo"             -- converts do blocks to bind notation
:def! index lb "index"           -- finds the module that defines the given identifier
:def! instances lb "instances"   -- finds all instances of a given type class
:def! src lb "src"               -- tries to find the source code for the given identifier
:def! oeis lb "oeis"             -- looks up the On-Line Encyclopedia of Integer Sequences (https://oeis.org/)

Another method to achieve the same thing is to import GOA and use the lambdabot function. However, using the lambdabot binary directly is simpler and works without importing extra modules that are not related to your project.

More Package and Documentation Lookup Commands

This snippet requires the ghc-paths module, and allows us to call ghc-pkg from GHCi:

:set -package ghc-paths
import GHC.Paths
:def! ghc_pkg (\s -> return $ ":!" ++ GHC.Paths.ghc_pkg ++ " " ++ s)
:m -GHC.Paths

For example:

~λ :ghc_pkg describe ghc-paths
name: ghc-paths
version: 0.1.0.9
id: ghc-paths-0.1.0.9-AeY5FiD7eih3ZffF6P7kJ1
key: ghc-paths-0.1.0.9-AeY5FiD7eih3ZffF6P7kJ1
license: BSD-3
copyright: (c) Simon Marlow
maintainer: Simon Marlow <marlowsd@gmail.com>
author: Simon Marlow
stability: stable
synopsis: Knowledge of GHC's installation directories
description:
    Knowledge of GHC's installation directories
category: Development
...

The following snippet requires the ghc-paths module, and creates the :docs command to look up the documentation for a given identifier:

:set -package ghc-paths
import GHC.Paths
docs s = return $ ":!echo file://" ++ GHC.Paths.docdir ++ "/../$(tr \\< \\\\n < " ++ GHC.Paths.docdir ++ "/../doc-index-All.html | grep -A100 -F \\>'" ++ s ++ "' | grep href | head -1 | cut -d\\\" -f2)":def! docs docs
:m -GHC.Paths

It can be used like such:

~λ :docs  ***
file:///Users/pdr/.stack/programs/x86_64-osx/ghc-8.6.4/share/doc/ghc-8.6.4/html/libraries/base-4.12.0.0/../base-4.12.0.0/Control-Arrow.html#v:-42--42--42-

Older GHCi Versions

There are many other snippets out there, but a lot of those have since been replaced by built-in functionality and/or no longer work under stack and cabal. Here is a list of how to achieve the same functionality that some old snippets used to provide:

  • -ghci-script replaces loading further startup scripts via an environment variable or other means
  • Pressing Ctrl-L clears the screen
  • :script sources other startup scripts

Frequently Asked Questions (FAQ)

How do I get GHCi to print the type of a function instead of an error?

There's no easy way to do this in general, but if you use :set +t as recommended above, you can simply create a Show instance for functions, which will output nothing. However, this won't work if GHCi can't work out what concrete types your function needs, and print an error anyway. In any case, this snippet will do that:

instance Show (a -> b) where show _ = ""
:set +t

And here it is in action:

~λ map

it :: (a -> b) -> [a] -> [b]

However, this simple trick doesn't work for everything:

~λ (<*>)

<interactive>:14:1: error:
    • Ambiguous type variable ‘f0’ arising from a use of ‘it’
      prevents the constraint ‘(Applicative f0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘f0’ should be.
      These potential instances exist:
        instance Arrow a => Applicative (ArrowMonad a)
          -- Defined in ‘Control.Arrow’
        instance Applicative (Either e) -- Defined in ‘Data.Either’
        instance Applicative IO -- Defined in ‘GHC.Base’
        ...plus three others
        ...plus 19 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the first argument of ‘print’, namely ‘it’
      In a stmt of an interactive GHCi command: print it

How do I stop GHCi from printing the result of a bind statement?

Sometimes you want to perform an IO action at the prompt that will produce a lot of data (e.g. reading a large file). When you try to do this, GHCi will helpfully spew this data all over your terminal, making the console temporarily unavailable.

To prevent this, use :set -fno-print-bind-result. If you want this option to be permanently set, add it to your .ghci file.