Confusion on `show` function in GHCI prompt

In the chapter “Higher Order Functions” of the book Learn You a Haskell For Great Good, the author wrote "When we type 1 + 1 in the GHCI prompt, then Haskell first calculate 2, then calls show on 2 then print on the screen.

This looks weird because in GHCI prompt I have the following :

ghci> 1 + 1
2 

ghci> show 2
"2"

If eventually Haskell calls show on 2, why not 1 + 1 returns "2". I try to read the document about show but I don’t get many information.

1 Like

The result of 1 + 1 is the number 2. A number isn’t a string, and only strings can be written to the screen. Since there are lots of things like numbers that are not strings but that a person might want to look at in GHCi, GHCi will call show on anything that it produces for you, whether it’s a string already or not. Then it writes the result of show to the screen, which is okay because the result of show is always a string!

When you write a string to the screen, it is written verbatim. If your program contains putStrLn "hello", you will see this:

hello

So when you type 1 + 1 into GHCi, first it is evaluated to the number 2. Then GHCi calls show on that, giving you the string "2". I have added quotes here because that’s how we talk about strings in Haskell, but they are not part of the string! This is a string that contains only one character: the digit 2. When GHCi writes the string "2" to the screen, all you see is its contents, verbatim, which is the lone digit 2.

When you type show 2 into GHCi, first it is evaluated to the string "2". Again I have added quotes here because that is how we talk about strings in Haskell. Then GHCi will call show on that, just like it calls show on everything it wants to pass back to you. "2" is a string already, but that doesn’t matter—you can still call show on a string! The result of calling show on the one-character string "2" is the three-character string "\"2\"". Once more, I have added quotes here because that is how we talk about strings in Haskell! When GHCi writes the string "\"2\"" to the screen, all you see is its contents, verbatim, which are the three characters "2".

3 Likes

Thank you very much! Now I can see the difference between the two processes.

I think you can interpret this as GHCi doing putStrLn (show _) of your expression:

ghci> 1 + 1
2
ghci> putStrLn (show (1 + 1))
2
ghci> "2"
"2"
ghci> putStrLn (show "2")
"2"
3 Likes

Yeah the book is off by one. It calls print, equivalently putStrLn (show ...). It doesn’t just call show.

1 Like