Haskell程序运行报错Prelude.readIO: no parse问题咨询
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:
getContentsreads all input until you send EOF (Ctrl+D on Unix/Linux, Ctrl+Z on Windows) as a single string.linessplits that string into a list of lines, ignoring the final newline.reverse inputLinesflips 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_ putStrLnprints each line directly—no need forshowhere 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

