Haskell/Using GHCi effectively
GHCi offers several ways to make you work faster. This section will describe them and explain what they are for.
User interface[edit]
Tab completion[edit]
Whenever you are typing anything into the GHCi, you can hit Tab and you will be presented with a list of all possible names that start with what you've written so far. And if there is only one way how to continue, the string will be auto-completed. For example fol<Tab> will append letter d, another Tab will list four functions: fold foldl1 foldr and foldr1. Only functions and other defined objects (e.g. Data types) from modules that are currently imported are offered.
Tab completion works also when you are loading a file with your program into GHCi. After typing :l fi<Tab>, you will be presented with all files that start with "fi" and are present in the current directory (the one you were in when you launched GHCi).
": commands"[edit]
On GHCi command line, commands for the interpreter start with the character ":" (colon).
- :help -- prints a list of all available commands.
- :load myfile.hs -- loads a file (here, "myfile.hs") into GHCi.
- :reload -- reloads the file that has been loaded last time, so changes are visible from GHCi.
- :type <Haskell expression> -- prints the type of a given expression, e.g. a function that has been defined previously.
- :module +Data.List -- loads a module (in this example,
Data.List
). You can also unload a module with:module -Data.List
. - :browse Data.List -- gives the type signatures for all functions available from a module.
Many of these commands can be abbreviated - :l for :load, :r for :reload, :h for :help, :t for :type and :m for module.
Timing Functions in GHCi[edit]
GHCi provides a basic way to measure how much time a function takes to run, which can be useful for people who quickly want to find out, for example, which version of a function runs faster.
- Type
:set +s
into the ghci command line. - run the function(s) you are testing. The time the function took to run will be displayed after GHCi outputs the results of the function.
Multi-line Input[edit]
If you are trying to define a function that takes up multiple lines, or if you want to type a do block into ghci, there is an easy way to do this:
- Begin a new line with
:{
- Type in your code. Press enter when you need a new line.
- Type
:}
to end the multiline input.
For example:
*Main> :{ *Main| let askname = do *Main| putStrLn "What is your name?" *Main| name <- getLine *Main| putStrLn $ "Hello " ++ name *Main| :} *Main>
In addition, line breaks in ghci commands can be separated by ;
, like this:
*Main> let askname1 = do ; putStrLn "what is your name?" ; name <- getLine ; putStrLn $ "Hello " ++ name