问题描述
我可以这样做:
Prelude>读取1 2 3:: [(Int,String)]
[(1,2 3)]
Prelude> (1,2)(3,4):: [((Int,Int),String)]
[((1,2),(3,4))]
前奏> (1,2)(3,4):: [((Int,Int),String)]
[((1,2),(3,4))]
前奏>读取(1,2)\\\
(3,4):: [((Int,Int),String)]
[((1,2),\\\
(3,4) )]
前奏> (1,2)(3,4):: [((Int,Int),String)]
[((1,2),(3,4))]
我可以派生读取并读取以读取它们。但是我从来没有得到过读取来返回列表中的多个元组。为什么读取返回一个列表?
没有标准实例这样做,但它的目的是模糊的分析;因为这不是非常有用,并且使用此功能的解析器效率非常低,所以的读取的返回值实际上是用于 Maybe 伪装成 [] 。
的定义揭示了多个解析的预期含义:
read ::(阅读a)=>字符串 - >
读取s = case [x | (x,t)< - 读取
[x] - >的s,(,) - lex t] x
[] - >错误PreludeText.read:no parse
_ - >错误PreludeText.read:ambiguous parse
因此:历史原因基本上。 b $ b
I can do the following:
Prelude> reads "1 2 3" :: [(Int, String)] [(1," 2 3")] Prelude> reads "(1,2) (3,4)" :: [((Int, Int), String)] [((1,2)," (3,4)")] Prelude> reads "(1,2)(3,4)" :: [((Int, Int), String)] [((1,2),"(3,4)")] Prelude> reads "(1,2)\n(3,4)" :: [((Int, Int), String)] [((1,2),"\n(3,4)")] Prelude> reads "(1,2) (3,4)" :: [((Int, Int), String)] [((1,2)," (3,4)")]
I can derive Read and get reads to read those too. But I've never gotten reads to return more than one tuple in the list. Why does reads return a list?
None of the standard instances do so, but it's intended for ambiguous parses; since this is not really very useful, and parsers that use this functionality would be very inefficient, reads's return value is for all practical purposes a Maybe masquerading as a [].
The Report's definition of read reveals the intended meaning of multiple parses:
read :: (Read a) => String -> a read s = case [x | (x,t) <- reads s, ("","") <- lex t] of [x] -> x [] -> error "PreludeText.read: no parse" _ -> error "PreludeText.read: ambiguous parse"
So: historical reasons, basically.
这篇关于Haskell的`reads`在哪些场景下返回多个列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!