Haskell 秒差距问题
我是 Haskell 新手,正在学习 Parsec lib 举个例子:
nesting :: Parser Int
nesting = do{ char '('
; n <- nesting
; char ')'
; m <- nesting
; return (max (n+1) m)
}
<|> return 0
n 或 m 是多少?为什么n和m是int并且大于0?
I am newbie haskell and in lernning parsec lib
a example :
nesting :: Parser Int
nesting = do{ char '('
; n <- nesting
; char ')'
; m <- nesting
; return (max (n+1) m)
}
<|> return 0
so what's n or m? why n and m is int and greater than 0?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Parsec 是一个单子解析库,因此您可能应该首先向自己介绍单子和语法糖,即 do 表示法。
nesting
是一个解析器,您可以将其视为具有Int
类型结果的计算(monad)。每当您在 do 块中看到类似
n <- Nesting
的代码时,这意味着运行 monad 嵌套并将结果绑定到n
。要了解此解析器的工作原理,请尝试手动运行它。例如,使用字符串“
()
”。它是这样的:
(
”,递归运行解析器并将结果绑定到n
。(
”失败,尝试下一个解析器 (return 0
),该解析器始终成功,且值为0< /代码>。
char ')'
,它成功了,再次递归调用解析器并将结果绑定到m
。与上面相同,m
中的结果是0
。现在整个计算结果是
max (n+1) m
,即1
。正如您所看到的,它解析嵌套括号,并且大致在顶层
n
保存解析的'('
的数量,而m
保存解析的')'
数量。Parsec is a monadic parsing library, so you probably should first introduce yourself to monads and the syntactic sugar that is the do notation.
nesting
is a parser which you can see as a computation (monad) with a result of typeInt
.Whenever you see code like this
n <- nesting
in a do block, it means run the monad nesting and bind the result ton
.To see how this parser works try running it by hand. For example use the string "
()
".It goes like this:
(
', runs the parser recursively and binds the result ton
.(
', tries the next parser (return 0
) which always succeeds with the value0
.n
now has the value 0, because that was the result of running the parser recursively. Next in the do block is the parserchar ')'
, it succeeds, calls the parser again recursively and binds the result tom
. Same as above the result inm
is0
.Now the whole result of the computation is
max (n+1) m
which is1
.As you can see this parses nested parenthesis, and roughly at the top level
n
holds the number of'('
parsed, whilem
holds the number of')'
parsed.