parsing - Haskell readLn 没有解析错误

标签 parsing haskell io

此功能允许用户输入字符串列表。该函数采用长度并允许用户输入长度为 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:无解析),我不知道为什么,任何想法?

最佳答案

这是因为您试图阅读错误类型的内容。

你说LineString又名。 [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/

相关文章:

java - 跟踪在 Java 中解析流时找到的最多 5 个值的最佳方法

haskell - 将字典变成约束

使用IO多路复用的Java echo服务器客户端

java - String Substring 故意删除字符 0

python - 如何根据缩进解析 block

haskell - ghc 的 FUN_1_0、FUN_0_1 等闭包类型是什么意思?

haskell - 如何正确强制评估 IO monad 中的纯值?

c - C 中传递给函数的结构体数组

c# - 系统.IO.IOException : file used by another process

zend-framework - 最佳实践 : Zend View: Load content from database and render PHP-code included in content