How to define a function in GHCi that spans multiple lines

Are you wondering how to define a function in GHCi that spans multiple lines? How can you provide explicit type signatures for a function? How can you copy and paste larger chunks of Haskell into the interpreter like you can in Python?

You can do all of these things, but unfortunately attempting them in the most obvious way will probably result in some of the errors below. Fortunately there is a fix, albeit a bit clunkier than what you can do in interpreters for languages like Python and R.

Don’t tell me about problems, I just want the solution.

GHCi makes it quick and easy to evaluate Haskell code when it’s limited to a single line, but trying to do these things in the obvious way will probably result in some of the errors below. Fortunately there is a fix, albeit a bit clunkier than what you may be able to do in language like Python or R.

Multi-line problems

Second line overrides the first

ghci>isNothing Nothing = True
ghci>isNothing (Just _) = False
...
ghci>isNothing Nothing
*** Exception: <interactive>:5:1-26: Non-exhaustive patterns in function isNothing

Trying to include a type signature

ghci>add :: Int -> Int -> Int
<interactive>:1:1: error:
    • Variable not in scope: add :: Int -> Int -> Int

Trying to paste a block of code directly

Copy/pasting the following:

data Shape =
    Circle Double
  | Rect Double Double

area :: Shape -> Double
area (Circle radius) = 3.1415 * radius * radius
area (Rect width height) = width * height

results in a whole bunch of errors:

<interactive>:1:13: error:
    parse error (possibly incorrect indentation or mismatched brackets)
<interactive>:2:5: error:
    Data constructor not in scope: Circle :: t0 -> t
<interactive>:2:12: error: Data constructor not in scope: Double
<interactive>:3:3: error: parse error on input ‘|’
<interactive>:5:9: error:
    Not in scope: type constructor or class ‘Shape’
<interactive>:6:7: error: Not in scope: data constructor ‘Circle’
<interactive>:7:7: error: Not in scope: data constructor ‘Rect’

Solution

The solution to all of these problems is the commands :{ and :}.

In between these two commands you can enter any multi-line Haskell code that you would normally write in a file as long as it doesn’t contain import statements.

  • Enter :{ on its own line.
  • Paste or type your code.
  • Enter :} on its own line.
ghci>:{
ghci>data Shape =
ghci>    Circle Double
ghci>  | Rect Double Double
ghci>
ghci>area :: Shape -> Double
ghci>area (Circle radius) = 3.1415 * radius * radius
ghci>area (Rect width height) = width * height
ghci>:}
ghci>area (Rect 20 100)
ghci>2000.0

Credits

Photo by Marvin Ronsdorf on Unsplash

jacobstanley.io

Menu