3
votes

In GHCi, I try to read string as tuple.

>reads "(1,2)" :: [(Integer),(Integer)]

which outputs the error:

Couldn't match type [Char] with Integer
expected type: [(Integer,Integer)]
actual type: [(Integer,String)]

The example I found online, and works is:

>reads "(34, True),abc" :: [((Integer,Bool),String)]
[((34,True),",abc")]

So why the one I try to create won't work?

1

1 Answers

8
votes

You have to account for the trailing String which reads always produces.

> reads "(1,2)" :: [((Integer,Integer),String)]
[((1,2),"")]

If you only want a single pair and are absolutely certain that the string parses correctly, use read instead

> read "(1,2)" :: (Integer,Integer)
(1,2)

Note that read (unlike reads) will crash your program on an invalid string. If you can not assume the string parses correctly, but you still want a single pair, use readMaybe instead form Text.Read.