How to convert string to tuple using `reads`?

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)]

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

1 answer

  • answered 2019-03-13 18:42 chi

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

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

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

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

    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.