在GHCi中,我尝试将字符串读取为元组。
>reads "(1,2)" :: [(Integer),(Integer)]
输出错误:
无法将类型[Char]与整数进行匹配
预期的类型:[(Integer,Integer)]
实际类型:[(Integer,String)]
我在网上找到的可行的示例是:
>reads "(34, True),abc" :: [((Integer,Bool),String)]
[((34,True),",abc")]
那为什么我尝试创建的那个不起作用?
答案 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
形式。