Show, Read and Text.Read

show

show turns a value into a String, and the derived instance produces Haskell syntax: quotes around strings, brackets around lists, the constructor names for custom types. That is what print uses, which is why a printed record of the last lesson looked like source code.

show (42 :: Int) -- "42" show [True, False] -- "[True,False]" show (Just 3 :: Maybe Int) -- "Just 3" show (Just "a") -- "Just \"a\""

The fourth line is the subtle one: the string inside the Maybe is shown with its quotes, so the result is a string containing escape characters. That is not a bug: the output is meant to be valid Haskell, and a valid Haskell string must be quoted.

read and its type

read is the other direction: it takes a String and returns a value, and the type of the value is not in the argument, so it must come from the context. read "42" alone is ambiguous; the annotation :: Int or the type of the surrounding expression fixes it.

module Main (main) where main :: IO () main = do print (show (42 :: Int)) print (read "42" :: Int) print (read "(1,2)" :: (Int, Int)) print (show [True, False] :: String) print (read "[1,2,3]" :: [Int])

ghc -Wall -O1 -o shownread shownread.hs
./shownread

"42"
42
(1,2)
"[True,False]"
[1,2,3]

The derived Read and the derived Show are inverse on the values the compiler can print and parse, which is why the pair is called a round trip. The types that can derive one can derive the other, and a hand-written Show with a derived Read breaks the property.

readMaybe and a parse that fails

read throws when the string is not a value of the requested type, which makes it unusable on user input. The Text.Read module has readMaybe :: Read a => String -> Maybe a, the total version that answers Nothing instead of crashing:

module Main (main) where import Text.Read (readMaybe) parseAge :: String -> Either String Int parseAge text = case readMaybe text of Nothing -> Left ("not a number: " ++ text) Just n | n < 0 -> Left "negative" | otherwise -> Right n main :: IO () main = do print (parseAge "36") print (parseAge "abc") print (parseAge "-5") print (readMaybe "3.5" :: Maybe Double)

ghc -Wall -O1 -o readmaybe readmaybe.hs
./readmaybe

Right 36
Left "not a number: abc"
Left "negative"
Just 3.5

Three outcomes and one type: a number, a string that is not a number, a number that is out of range. The Either of the last lesson carries the difference, and the program handles every case without an exception. This is the shape a command-line parser uses before it touches the rest of the program.

The round trip

read (show x) == x holds for every type whose Show and Read agree, and a program can check it. That property is what makes show useful for a log that a later run can parse, and it is the reason the derived instances print constructor names rather than a pretty format:

read (show (42 :: Int)) == 42 -- True read (show [True, False]) == [True, False] -- True read (show (Just 3 :: Maybe Int)) == Just 3 -- True

Two caveats. A hand-written Show that prints "2, 3" for a point has no matching Read, so the round trip is gone and the printed value is for people, not for the program. And read is slow compared with a real parser: it is fine for a configuration line and wrong for a million records, where the lessons on parsing come in.

Exercises

  1. Print show of a list of strings and count the quote characters in the output.
  2. Read a list of three integers from a string and print their sum.
  3. Write a function that reads a pair of numbers from one line with two readMaybe calls.
  4. Check the round trip for a record with a derived Show and Read.
  5. Give read a string that is not a number and read the exception message.
  6. Explain why read "42" without a type annotation does not compile.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does show (42 :: Int) return?

    Answer

    "42", a String with the digits

    show returns a String, and print adds the quotes when it displays that string.

  2. Why does read "42" need a type annotation?

    Answer

    read returns any Read type, so the context must choose one

    The result type cannot be inferred from the string alone, so the annotation fixes which Read instance to use.

  3. What does read "(1,2)" :: (Int, Int) return?

    Answer

    (1,2)

    The tuple instance parses the two numbers and builds the pair.

  4. What happens when read cannot parse the string?

    Answer

    It throws an exception at run time

    read is partial; readMaybe is the total version that returns Maybe.

  5. What does readMaybe "abc" :: Maybe Int return?

    Answer

    Nothing

    A string that is not a number parses to Nothing instead of throwing.

  6. What does this program print? module Main (main) where main :: IO () main = print (show [True, False] :: String)

    Answer

    "[True,False]"

    show of the list is a string with brackets and commas, and print shows that string with quotes.

  7. Which pair of instances makes read (show x) == x hold?

    Answer

    A derived Read and a derived Show for the same type

    The derived instances agree on the syntax, which is what the round trip needs.

  8. What does show (Just "a") return?

    Answer

    Just "\"a\"" as text, with escaped quotes

    The inner string is shown with quotes, and those quotes are escaped inside the outer string.

  9. Which function belongs in a program that reads a number from the user?

    Answer

    readMaybe, so a bad line is a value and not a crash

    User input can be wrong, and readMaybe turns the failure into Nothing for the program to handle.

  10. What does this program print? module Main (main) where main :: IO () main = print (read "[1,2,3]" :: [Int])

    Answer

    [1,2,3]

    The list instance parses the three numbers and print shows the list.

The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev