我正在尝试使用Prelude的reads
函数和doctest来测试它。只需加载GHCI并输入reads "57x"
或Prelude.reads "57x"
只会产生一个空列表[]
,所以我认为我必须自己导入该功能。根据文档,它应该返回一个元组。但是在运行Doctest和GHCI时,我在输入除了整数之外还有字符的任何测试时都会收到错误*** Exception: Prelude.read: no parse
,即54x
。我需要改变什么才能让它返回正确的元组,如here所述,但使用INT而不是DOUBLE?
我有一个看起来像这样的haskell文件:
module StackOverflow where
import Prelude hiding (words, reads)
reads :: String -> [(Int, String)]
-- ^ Takes a string, like "57" and reads the corresponding integer value
-- out of it. It returns an empty list if there is a failure, or a list
-- containing one tuple, with the integer value as the first element of
-- the tuple and a (possibly empty) string of remaining unconvertable extra
-- characters as the second element.
--
-- Examples:
--
-- >>> reads "57"
-- [(57,"")]
--
-- >>> reads "57x"
-- [(57,"x")]
--
reads s = [(read s :: Int,"")]
答案 0 :(得分:1)
您获得“无解析”异常的原因是该类型默认为Int
以外的其他内容(在本例中为()
)。因此,有效地,表达式reads "54x"
正在[((), String)]
类型进行评估。这是因为为了选择适当的Read
实例,必须在编译时完全指定类型,但这是不可能的,因为它不知道预期包含String
的内容。 / p>
您可以通过提供明确的类型签名来告诉它String
您期望的类型,例如
reads "54x" :: [(Int, String)]
所有表达式都可以给出一个显式的类型签名,事实上,为了避免模糊类型,有时需要它。