14
votes

Defining a function signature in Haskell's interpreter GHCi doesn't work. Copying an example from this page:

Prelude> square :: Int -> Int

<interactive>:60:1: error:
    • No instance for (Show (Int -> Int)) arising from a use of ‘print’
        (maybe you haven't applied a function to enough arguments?)
    • In a stmt of an interactive GHCi command: print it
Prelude> square x = x * x

How can I declare a function signature and then give function definition in Haskell interactively? also: why can't I simply evaluate the function and see its type (e.g. Prelude> square) once it has been defined?

3

3 Answers

28
votes

You can define a function signature in the ghc interactive shell. The problem however is that you need to define functions in a single command.

You can use a semicolon (;) to split between two parts:

Prelude> square :: Int -> Int; square x = x * x

Note that the same holds for a function with multiple clauses. If you write:

Prelude> is_empty [] = True
Prelude> is_empty (_:_) = False

You have actually overwritten the previous is_empty function with the second statement. If we then query with an empty list, we get:

Prelude> is_empty []
*** Exception: <interactive>:4:1-22: Non-exhaustive patterns in function is_empty

So ghci took the last definition as a single clause function definition.

Again you have to write it like:

Prelude> is_empty[] = True; is_empty (_:_) = False
15
votes

Multi-line input needs to be wrapped in the :{ and :} commands.

λ> :{
 > square :: Int -> Int
 > square x = x * x
 > :}
square :: Int -> Int
8
votes

Here are three ways:

>>> square :: Int -> Int; square = (^2)
>>> let square :: Int -> Int
...     square = (^2)
...
>>> :{
... square :: Int -> Int
... square = (^2)
... :}

The second one requires you to :set +m; I include this in my ~/.ghci so that it is always on.