Using GHCi
Prerequisites: Your first program
GHCi is where you'll explore Haskell: evaluate expressions, check types, and test functions as you write them.
Evaluating and defining
ghci> 2 + 3 * 4
14
ghci> let double x = x * 2
ghci> double 21
42
ghci> triple x = x * 3
ghci> triple 5
15
ghci> it + 1
16
- You can define values and functions directly (the
letis optional in modern GHCi). itholds the result of the last expression.
Asking for types and info
ghci> :t 'a'
'a' :: Char
ghci> :t not
not :: Bool -> Bool
ghci> :t "hello"
"hello" :: String
ghci> :i Bool
type Bool :: *
data Bool = False | True
-- Defined in `GHC.Internal.Types'
instance Bounded Bool -- Defined in `GHC.Internal.Enum'
instance Read Bool -- Defined in `GHC.Internal.Read'
instance Enum Bool -- Defined in `GHC.Internal.Enum'
instance Eq Bool -- Defined in `GHC.Internal.Classes'
instance Ord Bool -- Defined in `GHC.Internal.Classes'
instance Show Bool -- Defined in `GHC.Internal.Show'
:t expr(:type) shows the type of any expression. You'll use this constantly.:i name(:info) shows how a type, function, or class is defined and which instances it has. (Depending on your terminal, GHC quotes names with‘ ’or with` '.)
Loading files
Save functions in a file, for example Shapes.hs:
-- illustrative: loaded into GHCi, no main
area :: Double -> Double
area r = pi * r * r
ghci> :l Shapes.hs
[1 of 2] Compiling Main ( Shapes.hs, interpreted )
Ok, one module loaded.
ghci> area 2
12.566370614359172
ghci> :r
Ok, one module reloaded.
:l (:load) loads a file; after editing it, :r (:reload) picks up
the changes. A good workflow is editor on one side, GHCi on the other.
Handy commands
| Command | What it does |
|---|---|
:t expr |
Type of an expression |
:i name |
Information about a name |
:l file / :r |
Load / reload |
:browse Data.Char |
List everything a module exports |
:m + Data.List |
Bring a module into scope (or import Data.List) |
:{ ... :} |
Enter a multi-line definition |
:q |
Quit |
Running one expression
ghc -e evaluates an expression without starting the REPL:
$ ghc -e "sum [1..100]"
5050