gdr*_*les 9 io parsing haskell
此功能允许用户输入字符串列表.该函数采用长度并允许用户输入长度为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
Run Code Online (Sandbox Code Playgroud)
Line的类型为String.
当我尝试运行该函数并输入..说["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
Run Code Online (Sandbox Code Playgroud)
如果你真的想输入行,那么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
Run Code Online (Sandbox Code Playgroud)
如果有任何帮助,您的程序会接受以下输入:
*Main> readme
"abc"
"123"
"456"
["abc","123","456"]
Run Code Online (Sandbox Code Playgroud)
您可能打算写getLine而不是readLn,但不知道您的程序的目的,这有点难以辨别.
更改为getLine,程序接受:
*Main> readme
abc
123
456
["abc","123","456"]
Run Code Online (Sandbox Code Playgroud)