如何使用`reads`将字符串转换为元组?

时间:2019-03-13 18:34:09

标签: string haskell

在GHCi中,我尝试将字符串读取为元组。

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

输出错误:

  

无法将类型[Char]与整数进行匹配
  预期的类型:[(Integer,Integer)]
  实际类型:[(Integer,String)]

我在网上找到的可行的示例是:

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

那为什么我尝试创建的那个不起作用?

1 个答案:

答案 0 :(得分:8)

您必须考虑String总是产生的结尾reads

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

如果只希望使用一对,并且绝对确定该字符串可以正确解析,请改用read

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

请注意,read(与reads不同)会使程序在无效字符串上崩溃。如果您不能假定字符串可以正确解析,但是仍然希望使用一对,请使用readMaybe而不是Text.Read形式。