You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell程序运行报错Prelude.readIO: no parse问题咨询

Fixing the "Prelude.readIO: no parse" Error in Your Haskell Line-Repeating Program

Hey there, let’s figure out why your program is throwing that parse error and get it working exactly as you want.

The Root Cause of the Error

That user error (Prelude.readIO: no parse) message is a classic sign you’re using read (or readIO) to handle plain text input. Here’s the catch: read expects input to be a valid Haskell literal. For strings, that means wrapping your input in double quotes (like "LINE 1"), but you’re entering unquoted lines like LINE 1—so read can’t make sense of it, hence the parse failure.

Looking at your code snippet, it’s almost certain your readlist function is using readIO instead of getLine to read each line. getLine is the right tool here because it reads plain text lines exactly as you enter them, no quotes required.

A Working Version of Your Program

Here’s a complete, idiomatic Haskell program that does exactly what you described: reads arbitrary lines until EOF, repeats each line twice, then outputs everything in reverse order:

main :: IO ()
main = do
    -- Read all input until EOF, split into individual lines
    inputLines <- lines <$> getContents
    -- Reverse the input lines, then duplicate each one twice
    let processedLines = concatMap (\line -> [line, line]) (reverse inputLines)
    -- Print each processed line to the console
    mapM_ putStrLn processedLines

Let’s Break This Down:

  • getContents reads all input until you send EOF (Ctrl+D on Unix/Linux, Ctrl+Z on Windows) as a single string. lines splits that string into a list of lines, ignoring the final newline.
  • reverse inputLines flips the order of your input so we start with the last line you entered.
  • concatMap (\line -> [line, line]) takes each reversed line and duplicates it, turning ["LINE 2"] into ["LINE 2", "LINE 2"], then flattens all these into one continuous list.
  • mapM_ putStrLn prints each line directly—no need for show here since we’re working with plain strings.

Testing the Program

Compile with ghc filename.hs, run the executable, then enter:

LINE 1
LINE 2

Hit EOF, and you’ll get the expected output:

LINE 2
LINE 2
LINE 1
LINE 1

What Went Wrong in Your Original Code

If your readlist function looked something like this (a common beginner mistake):

readlist :: [String] -> IO [String]
readlist acc = do
    line <- readIO
    readlist (line : acc)

That’s where the error comes from—readIO tries to parse your unquoted input as a Haskell string literal, which it can’t do. Even if you swapped readIO for getLine, using getContents is a cleaner, more Haskell-y way to read all lines until EOF.


内容的提问来源于stack exchange,提问作者vivek sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:46:28