Part 15

Let’s Start

Let’s Start!

GHCi is the interactive Haskell interpreter. Here’s an example session:

$ stack ghci
GHCi, version 9.2.8: https://www.haskell.org/ghc/  :? for help
Prelude> 1+1
2
Prelude> "asdf"
"asdf"
Prelude> reverse "asdf"
"fdsa"
Prelude> :type "asdf"
"asdf" :: [Char]
Prelude> tail "asdf"
"sdf"
Prelude> :type tail "asdf"
tail "asdf" :: [Char]
Prelude> :type tail
tail :: [a] -> [a]
Prelude> :quit
Leaving GHCi.

By the way, the first time you run stack ghci it will download GHC and some libraries, so don’t worry if you see some output and have to wait for a while before getting the Prelude> prompt.

Let’s walk through this. Don’t worry if you don’t understand things yet, this is just a first brush with expressions and types.

Prelude> 1+1
2

The Prelude> is the GHCi prompt. It indicates we can use the functions from the Haskell base library called Prelude. We evaluate 1 plus 1, and the result is 2.

Prelude> "asdf"
"asdf"

Here we evaluate a string literal, and the result is the same string.

Prelude> reverse "asdf"
"fdsa"

Here we compute the reverse of a string by applying the function reverse to the value "asdf".

Prelude> :type "asdf"
"asdf" :: [Char]

In addition to evaluating expressions we can also ask for their type with the :type (abbreviated :t) GHCi command. The type of "asdf" is a list of characters. Commands that start with : are part of the user interface of GHCi, not part of the Haskell language.

Prelude> tail "asdf"
"sdf"
Prelude> :t tail "asdf"
tail "asdf" :: [Char]

The tail function works on lists and returns all except the first element of the list. Here we see tail applied to "asdf". We also check the type of the expression, and it is a list of characters, as expected.

Prelude> :t tail
tail :: [a] -> [a]

Finally, here’s the type of the tail function. It takes a list of any type as an argument, and returns a list of the same type.

Prelude> :quit
Leaving GHCi.

That’s how you quit GHCi.

You have reached the end of this section! Continue to the next section:

You can check your current points from the blue blob in the bottom-right corner of the page.