此功能允许用户输入字符串列表。该函数采用长度并允许用户输入长度为 1 的更多行。然后检查每一行以确保它与原始行的长度相同。编码:
readme :: IO [Line]
readme = do
line <- readLn
let count = length line
lines <- replicateM (count-1) $ do
line <- readLn
if length line /= count
then fail "too long or too short"
else return line
return $ line : lines
行是字符串类型。
当我尝试运行函数并输入..say ["12","13"] 时,我得到以下信息:* 异常:用户错误(Prelude.readIO:无解析),我不知道为什么,任何想法?
最佳答案
这是因为您试图阅读错误类型的内容。
你说Line
是 String
又名。 [Char]
.但是,您输入的输入格式为 ["12", "13"]
看起来应该是类型 [Line]
,又名。 [String]
或 [[Char]]
.
你需要解释什么是 Line
实际上应该是。如果您想要 Line
要成为一个字符串,那你为什么要在终端输入字符串列表?在这种情况下,您的逻辑有问题。
如果你想要输入方阵的方法,可以让type Line = [Int]
而是使用以下格式之一:
-- What you type at the terminal:
1 -2 3
4 5 6
6 7 8
-- How to read it in your program:
line <- (map read . words) `fmap` getLine
-- What you type at the terminal:
[1, -2, 3]
[4, 5, 6]
[6, 7, 8]
-- How to read it in your program:
line <- readLn
如果你真的想输入行,那么
type Line = [Char]
,并且输入列表中的每个数字都变成一个 unicode 字符,这意味着当您输入 [97, 98, 99]
在终端上,你会得到字符串 "abc"
:-- What you type at the terminal:
[97, 98, 99]
[100, 101, 102]
[103, 104, 105]
-- How to read it in your program:
line <- (map toEnum) `fmap` readLn
关于parsing - Haskell readLn 没有解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9667412/