Difference between revisions of "GHC/GHCi"

From HaskellWiki
< GHC
Jump to navigation Jump to search
(-fno-print-bind-result is a common FAQ)
m (Fixed incorrect usage of \STX (which may have caused problems with line wrapping))
 
(23 intermediate revisions by 14 users not shown)
Line 1: Line 1:
 
[[Category:GHC|GHCi]]
 
[[Category:GHC|GHCi]]
== Using GHCi ==
 
   
  +
= Introduction =
This page is a place to collect advice about how to use GHC's interactive interpreter, GHCi. Please add to it!
 
   
  +
GHCi is GHC's interactive environment, in which Haskell expressions can be interactively evaluated and programs can be interpreted. Before reading this, read the [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html GHCi section] of the [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ GHC User's Guide].
=== External tool integration ===
 
   
  +
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!
External command-line tools like [[Hoogle]] can be integrated in GHCi by adding a line to .ghci similar to
 
  +
<haskell>
 
  +
= Invoking GHCi =
:def hoogle \str -> return $ ":! hoogle -n 15 \"" ++ str ++ "\""
 
  +
  +
GHCi can be run in a number of ways, depending on your setup and requirements:
  +
  +
# standalone: <tt>ghci</tt>
  +
# within the stack global project: <tt>stack repl</tt>
  +
# within a specific stack project: <tt>cd project; stack repl</tt>
  +
# within a specific stack project, but including <tt>GHC_PACKAGE_PATH</tt>: <tt>cd project; stack exec ghci</tt>
  +
# within a temporary "fake" cabal project: <tt>cabal new-repl</tt>
  +
# within a specific cabal project: <tt>cd project; cabal new-repl</tt>
  +
  +
= Customisation =
  +
  +
When invoked, GHCi tries to load a startup script. The [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html#the-ghci-files 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 <tt>~/.ghci</tt>, 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 <tt>.bashrc</tt> (or equivalent for other shells):
  +
alias ghci='ghci -v0 -ignore-dot-ghci -ghci-script ~/.ghci.standalone'
  +
  +
This will make GHCi load the <tt>~/.ghci.standalone</tt> startup file instead, and there you can be free to load and use modules that you know are available in that environment. The <tt>-v0</tt> 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 [https://hackage.haskell.org/package/haskeline haskeline], which can also be [https://github.com/judah/haskeline/wiki/UserPreferences customized]. A typical <tt>~/.haskeline</tt> 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 <tt>set -o vi</tt>) add also the following line:
  +
editMode: Vi
  +
  +
= The Snippet Library =
  +
  +
The following is the recommended basis for the <tt>.ghci</tt> file:
  +
<haskell style="background:transparent">
  +
-- 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
 
</haskell>
 
</haskell>
   
  +
== Fancy Prompts ==
Make sure that the directory containing the executable is in your PATH environment variable or modify the line to point directly to the executable. Invoke the executable with commands like
 
  +
<haskell>
 
  +
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 [https://github.com/ryanoasis/nerd-fonts Nerd Fonts]. This is easily done using [https://brew.sh/ brew]:
:hoogle map
 
  +
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 <tt>directory</tt> module to configure a nice prompt:
  +
<haskell style="background:transparent">
  +
:{
  +
: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 [ "\ESC[33m\STX", pwd, main_module, "\ESC[37m\STX", promptString, " \ESC[0m\STX" ]
  +
where
  +
head' (x:_) = " \ESC[38;5;227m\STX" ++ 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\STX\xe61f"
  +
:set prompt-cont-function dotGHCI_myPrompt "∷"
 
</haskell>
 
</haskell>
   
  +
The following snippet works without loading extra modules, but requires a [https://en.wikipedia.org/wiki/POSIX POSIX] environment.
=== Using :def ===
 
  +
<haskell style="background:transparent">
  +
:{
  +
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 [ "\ESC[33m\STX", pwd, main_module, "\ESC[37m\STX", promptString, " \ESC[0m\STX" ]
  +
where
  +
head' (x:_) = " \ESC[38;5;227m\STX" ++ 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\STX\xe61f"
  +
:set prompt-cont-function dotGHCI_myPrompt "∷"
  +
</haskell>
   
  +
And here's what this should look like:
The <tt>:def</tt> command, documented [http://www.haskell.org/ghc/docs/latest/html/users_guide/ghci-commands.html here], allows quite GHCi's commands to be extended in quite a powerful way.
 
  +
<span style="color:orange">~</span>$ cd src/gitit
  +
<span style="color:orange">~/src/gitit</span>$ ghci src/Network/Gitit.hs
  +
<span style="color:orange">~/src/gitit</span> <span style="color:#e0e030; font-weight:800">Network.Gitit</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :info wiki
  +
wiki :: Config -> ServerPart Response
  +
-- Defined at src/Network/Gitit.hs:133:1
  +
<span style="color:orange">~/src/gitit</span> <span style="color:#e0e030; font-weight:800">Network.Gitit</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span>
   
  +
== Pretty Printing ==
Here is one example.
 
<pre>
 
Prelude> let loop = do { l <- getLine; if l == "\^D" then return () else do appendFile "foo.hs" (l++"\n"); loop }
 
Prelude> :def pasteCode (\_ -> loop >> return ":load foo.hs")
 
</pre>
 
This defines a new command <tt>:pasteCode</tt>, which allows you to paste Haskell code diretly into GHCi. You type the command <tt>:pasteCode</tt>, followed by the code you want, followed by <tt>^D</tt>, followed (unfortunately) by enter, and your code is executed. Thus:
 
<pre>
 
Prelude> :pasteCode
 
x = 42
 
^D
 
Compiling Main ( foo.hs, interpreted )
 
Ok, modules loaded: Main.
 
*Main> x
 
42
 
*Main>
 
</pre>
 
   
  +
GHCi's [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html#using-a-custom-interactive-printing-function <tt>-interactive-print</tt> option] allows for interactive output to be piped through a pretty printer. Here is a snippet, with custom colours:
=== A readline-aware GHCi on Windows ===
 
  +
<haskell style="background:transparent">
  +
-- 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
  +
</haskell>
   
  +
The following snippet works without loading extra modules, but requires the <tt>ppsh</tt> and <tt>HsColour</tt> binaries (from [https://hackage.haskell.org/package/pretty-show <tt>pretty-show</tt>] and [https://hackage.haskell.org/package/hscolour <tt>hscolour</tt>]) to be installed in your PATH.
Mauricio reports: I've just uploaded a package (<tt>rlwrap</tt>) to Cygwin that I like to use with <tt>ghci</tt>. You can use it like this:
 
  +
<haskell style="background:transparent">
<pre>
 
  +
-- Colourise ghci output (use :nopretty to disable)
rlwrap ghcii.sh
 
  +
:{
</pre>
 
  +
:def! pretty \_ -> return $ unlines [
and then you will use <tt>ghc</tt> as if it were readline aware (i.e., you can
 
  +
":unset +t",
press up arrow to get last typed lines etc.). <tt>rlwrap</tt> is very stable
 
  +
"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 }",
and I never had unexpected results while using it.
 
  +
":seti -interactive-print pp",
  +
":set +t"
  +
]
  +
:}
  +
:def! nopretty \_ -> return ":set -interactive-print System.IO.print"
  +
:pretty
  +
:unset +t
  +
</haskell>
   
  +
After adding all that, you should have a slightly nicer output from GHCi:
Since the issue of <tt>ghci</tt> integration with terminals has been raised
 
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> [1,2,3]
here sometimes, I thought some guys here would be interested (actually,
 
  +
<span style="color:red">[</span> <span style="color:#caaaec">1</span> , <span style="color:#caaaec">2</span> , <span style="color:#caaaec">3</span> <span style="color:red">]</span>
I found rlwrap looking for a better way to use ghci).
 
  +
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 <tt>ls</tt> command by simply using the operating system's <tt>ls</tt>:
  +
<haskell style="background:transparent">
  +
:def! ls \s -> return $ ":!ls " ++ s
  +
</haskell>
  +
  +
And you use these definitions by simply calling them with a colon, just like the builtin GHCi commands:
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :ls -1adF
  +
./
  +
../
  +
example.hs
  +
  +
=== HLint and Hoogle ===
  +
  +
Similarly, after installing the [http://hackage.haskell.org/package/hoogle <tt>hoogle</tt>] and [http://hackage.haskell.org/package/hlint <tt>hlint</tt>] binaries:
  +
<haskell style="background:transparent">
  +
dotGHCI_escapeShellArg arg = "'" ++ concatMap (\c -> if c == '\'' then "'\\''" else [c]) arg ++ "'"
  +
:def! hoogle return . (":!hoogle -q --count=15 --color " ++) . dotGHCI_escapeShellArg
  +
:def! search return . (":!hoogle -q --count=3 --color " ++) . dotGHCI_escapeShellArg
  +
:def! doc return . (":!hoogle -q --color --info " ++) . dotGHCI_escapeShellArg
  +
:def! hlint \s -> return $ ":!hlint " ++ if null s then "." else s
  +
</haskell>
  +
  +
This allows you to do the following from within GHCi:
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :hlint
  +
No hints
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :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
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :search is:exact <$>
  +
Prelude (<$>) :: Functor f => (a -> b) -> f a -> f b
  +
Control.Applicative (<$>) :: Functor f => (a -> b) -> f a -> f b
  +
Data.Functor (<$>) :: Functor f => (a -> b) -> f a -> f b
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :doc <*>
  +
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
  +
base Prelude
  +
Sequential application.
  +
  +
A few functors support an implementation of <*> that is
  +
more efficient than the default one.
  +
  +
=== Lambdabot Commands ===
  +
  +
There is an IRC bot called [http://hackage.haskell.org/package/lambdabot <tt>lambdabot</tt>] which includes many tools which can be accessed directly in "offline" mode. Here are some example usages:
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :pl \x y -> x + 1 -- converts code to point-free (aka pointless) form
  +
const . (1 +)
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :unpl const . (1 +) -- converts back from point-free (aka pointless) form
  +
(\ x _ -> 1 + x)
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :do getLine >>= putStrLn -- converts binds to do notation
  +
do { a <- getLine; putStrLn a}
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :undo do { a <- getLine; putStrLn a } -- converts do blocks to bind notation
  +
getLine >>= \ a -> putStrLn a
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :index <<^ -- finds the module that defines the given identifier
  +
Control.Arrow
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :instances Arrow -- finds all instances of a given type class
  +
(->), Kleisli m
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :src <<^ -- tries to find the source code for the given identifier
  +
a <<^ f = a <<< arr f
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :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:
  +
<haskell style="background:transparent">
  +
dotGHCI_escapeShellArg arg = "'" ++ concatMap (\c -> if c == '\'' then "'\\''" else [c]) arg ++ "'"
  +
lb s1 s2 = return $ ":!lambdabot -n -e " ++ dotGHCI_escapeShellArg s1 ++ "\\ " ++ dotGHCI_escapeShellArg 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/)
  +
</haskell>
  +
  +
Another method to achieve the same thing is to import <tt>GOA</tt> and use the <tt>lambdabot</tt> function. However, using the <tt>lambdabot</tt> 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 <tt>ghc-pkg</tt> from GHCi:
  +
<haskell style="background:transparent">
  +
:set -package ghc-paths
  +
import GHC.Paths
  +
:def! ghc_pkg (\s -> return $ ":!" ++ GHC.Paths.ghc_pkg ++ " " ++ s)
  +
:m -GHC.Paths
  +
</haskell>
  +
  +
For example:
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :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 <tt>:docs</tt> command to look up the documentation for a given identifier:
  +
<haskell style="background:transparent">
  +
:set -package ghc-paths
  +
import GHC.Paths
  +
:{
  +
dotGHCI_escapeShellHTMLArg arg = "'" ++ concatMap (\c -> case c of
  +
'\'' -> "'\\''"
  +
'>' -> "&gt;"
  +
'<' -> "&lt;"
  +
'&' -> "&amp;"
  +
_ -> [c]) arg ++ "'"
  +
:}
  +
docs s = return $ ":!echo file://" ++ GHC.Paths.docdir ++ "/../$(tr \\< \\\\n < " ++ GHC.Paths.docdir ++ "/../doc-index-All.html | grep -A100 -F \\>" ++ dotGHCI_escapeShellHTMLArg s ++ " | grep href | head -1 | cut -d\\\" -f2)"
  +
:def! docs docs
  +
:m -GHC.Paths
  +
</haskell>
  +
  +
It can be used like such:
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> :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:
  +
* [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html#ghc-flag--ghci-script <tt>-ghci-script</tt>] replaces loading further startup scripts via an environment variable or other means
  +
* Pressing Ctrl-L clears the screen
  +
* <tt>:script</tt> 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 <tt>:set +t</tt> as recommended above, you can simply create a <tt>Show</tt> 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:
  +
  +
<haskell style="background:transparent">
  +
instance Show (a -> b) where show _ = ""
  +
:set +t
  +
</haskell>
   
  +
And here it is in action:
------------------------
 
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> map
  +
  +
it :: (a -> b) -> [a] -> [b]
  +
However, this simple trick doesn't work for everything:
  +
<span style="color:orange">~</span><span style="color:#b860ff; font-weight:1000">'''λ'''</span> (<*>)
  +
  +
<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? ==
 
== 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.
+
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 <tt>:set -fno-print-bind-result</tt>. If you want this option to be permanently set, add it to your <tt>.ghci</tt> file.
 
To prevent this, use <tt>:set -fno-print-bind-result</tt>. If you want this option to be permanently set, add it to your <tt>.ghci</tt> file.

Latest revision as of 12:03, 15 May 2020


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 haskeline, 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 [ "\ESC[33m\STX", pwd, main_module, "\ESC[37m\STX", promptString, " \ESC[0m\STX" ]
  where
    head' (x:_) = " \ESC[38;5;227m\STX" ++ 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\STX\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 [ "\ESC[33m\STX", pwd, main_module, "\ESC[37m\STX", promptString, " \ESC[0m\STX" ]
  where
    head' (x:_) = " \ESC[38;5;227m\STX" ++ 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\STX\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:

dotGHCI_escapeShellArg arg = "'" ++ concatMap (\c -> if c == '\'' then "'\\''" else [c]) arg ++ "'"
:def! hoogle return . (":!hoogle -q --count=15 --color " ++) . dotGHCI_escapeShellArg
:def! search return . (":!hoogle -q --count=3 --color " ++) . dotGHCI_escapeShellArg
:def! doc return . (":!hoogle -q --color --info " ++) . dotGHCI_escapeShellArg
: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
~λ :search is:exact <$>
Prelude (<$>) :: Functor f => (a -> b) -> f a -> f b
Control.Applicative (<$>) :: Functor f => (a -> b) -> f a -> f b
Data.Functor (<$>) :: Functor f => (a -> b) -> f a -> f b
~λ :doc <*>
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
base Prelude
Sequential application.

A few functors support an implementation of <*> that is
more efficient than the default one.

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:

dotGHCI_escapeShellArg arg = "'" ++ concatMap (\c -> if c == '\'' then "'\\''" else [c]) arg ++ "'"
lb s1 s2 = return $ ":!lambdabot -n -e " ++ dotGHCI_escapeShellArg s1 ++ "\\ " ++ dotGHCI_escapeShellArg 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
:{
dotGHCI_escapeShellHTMLArg arg = "'" ++ concatMap (\c -> case c of
                                                         '\'' -> "'\\''"
                                                         '>' -> "&gt;"
                                                         '<' -> "&lt;"
                                                         '&' -> "&amp;"
                                                         _    -> [c]) arg ++ "'"
:}
docs s = return $ ":!echo file://" ++ GHC.Paths.docdir ++ "/../$(tr \\< \\\\n < " ++ GHC.Paths.docdir ++ "/../doc-index-All.html | grep -A100 -F \\>" ++ dotGHCI_escapeShellHTMLArg 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.