Skip to content

Evaluating Expressions

There are three types of things you can enter at the GHCi prompt:

  • GHCi commands, starting with a colon, such as the :quit command above.
  • Haskell expressions. When you do this, the expression gets evaluated, and the result is printed.
  • Definitions of types, values, and function.

Let's look at expressions briefly, just so you get some feel for them. Arithmetic expressions are written the same in Haskell as in any other language:

GHCi
>>> 2 * (3 + 5)
8

Or you could try a comparison:

GHCi
>>> False < True
True

Or some predicate, for example whether a given number is even or odd:

GHCi
>>> even 15
False
>>> odd 15
True

Any valid expression can be evaluated from the GHCi prompt, but GHCi may not know how to print the result. For example, as discussed shortly, we can define a function at the GHCi prompt:

GHCi
>>> double x = 2 * x

If we apply this function to some integer, the result is another integer, and GHCi knows how to print integers:

GHCi
>>> double 15
30

What if we try to print the function itself?

GHCi
>>> double

<interactive>:21:1: error:
    • No instance for (Show (Integer -> Integer))
        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

This doesn't work, and GHCi tells us why. It says "No instance for (Show (Integer -> Integer)). It deduced that double is a function of type Integer -> Integer—it maps an integer argument to an integer result. Show is the class of all types that can be printed in some human-readable format. The error message says that the function type Integer -> Integer has not been defined to be an instance of this type class; we have not defined how to print functions.