我试图输入一个整数列表并打印出来,但我得到了这个错误:Prelude.read: no parse
代码如下:
main = do
putStrLn "Enter a list of integers:"
input <- getLine
let xs = read input :: [Int]
putStr "The entered list is: "
print xs
输入:
2 4 6 8
预期输出:
The entered list is: 2 4 6 8
实际产量:
The entered list is: Sample: Prelude.read: no parse
1条答案
按热度按时间vjhs03f71#
问题是以下表达式失败:
类型
[Int]
的read
解析器期望读取一个包含有效Haskell语法列表的字符串:并且不接受空格分隔的整数列表。阅读一个 single integer仍然需要该单个整数是有效的Haskell格式,但由于这只是编写整数字面量的常用方式,因此它可以按预期工作:
所以,你可以使用函数
words
将字符串"1 2 3 4"
分成每个包含一个整数的字符串:然后
map
read
函数在结果字符串列表上,一次一个整数:修订后的方案:
如果您想以输入的方式打印列表,可以将
print xs
替换为:这里,表达式
unwords (map show xs)
是map read (words input)
的逆表达式,它将列表恢复为原始字符串格式。