为什么Prelude.read在Haskell中打印整数列表时会出现“www.example.com:no parse”错误?

k5hmc34c  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(161)

我试图输入一个整数列表并打印出来,但我得到了这个错误: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
vjhs03f7

vjhs03f71#

问题是以下表达式失败:

ghci>  read "1 2 3 4" :: [Int]
*** Exception: Prelude.read: no parse

类型[Int]read解析器期望读取一个包含有效Haskell语法列表的字符串:

ghci> read "[1,2,3,4]" :: [Int]
[1,2,3,4]

并且不接受空格分隔的整数列表。阅读一个 single integer仍然需要该单个整数是有效的Haskell格式,但由于这只是编写整数字面量的常用方式,因此它可以按预期工作:

ghci> read "1" :: Int
1

所以,你可以使用函数words将字符串"1 2 3 4"分成每个包含一个整数的字符串:

ghci> words "1 2 3 4"
["1","2","3","4"]

然后mapread函数在结果字符串列表上,一次一个整数:

ghci> map read (words "1 2 3 4") :: [Int]
[1,2,3,4]

修订后的方案:

main = do
    putStrLn "Enter a list of integers:"
    input <- getLine
    let xs = map read (words input) :: [Int]
    putStr "The entered list is: "
    print xs
  • almost* 可以做你想要的,除了它用Haskell语法打印列表:
Enter a list of integers:
1 2 3 4
The entered list is: [1,2,3,4]    <-- Haskell syntax for list

如果您想以输入的方式打印列表,可以将print xs替换为:

putStrLn (unwords (map show xs))

这里,表达式unwords (map show xs)map read (words input)的逆表达式,它将列表恢复为原始字符串格式。

相关问题