[英]How to correctly discard result of a (monadic) computation in F#
In Haskell, I can write: 在Haskell中,我可以写:
token: Parser a -> Parser a
token p = do space
v <- p
space
return v
In F#, I have come this far: 在F#中,我走了这么远:
let token = compose {
let! _ = space
let! v = parser
let! _ = space
return v
}
In other words, I have to introduce this unused let! _ =
换句话说,我必须介绍这个未使用的
let! _ =
let! _ =
binding to discard the parse value of "space" parser (monad), that I don't need. let! _ =
绑定以放弃我不需要的“空间”解析器(monad)的解析值。
How to avoid these useless bindings in F#? 如何避免在F#中这些无用的绑定? I have tried using do!, but I get an error (because my
>>=
function does not take type unit but 'a): 我尝试使用do !,但出现错误(因为我的
>>=
函数未采用类型单位而是'a):
let (>>=) (p: Parser<'a>) (f: 'a -> Parser<'b>) : Parser<'b>
Here is my builder definition: 这是我的构建器定义:
type ParserComposer() =
member x.Bind(p, f) = p >>= f
member x.Return(y) = ret y
member x.Zero() = failure
Do I need to define >>
function? 我需要定义
>>
函数吗? Add Combine() to builder? 将Combine()添加到生成器? Any ideas how to do this right?
任何想法如何正确执行此操作? Code example?
代码示例?
Assuming the return type of space
is Parser<unit>
(which would make sense if it does not represent a parser that returns some result) you can write: 假设
space
的返回类型是Parser<unit>
(如果它不代表返回某些结果的解析器,则很有意义),您可以编写:
let token = compose {
do! space
let! v = parser
do! space
return v
}
This is just a syntactic sugar for what you wrote - so do! e
这只是您编写内容的语法糖-这样
do! e
do! e
is translated as let! _ = e
do! e
被翻译为let! _ = e
let! _ = e
which is, in turn, translated to parser.Bind(e, fun _ -> ...)
. let! _ = e
,然后将其翻译为parser.Bind(e, fun _ -> ...)
。 I have a sample for Additive parsers on Try Joinads which also defines Combine
and a few more (possibly) useful things, but the do!
我在Try Joinads上有一个用于加法解析器的示例,该示例还定义了
Combine
和更多(可能)有用的东西,但是do!
keyword only needs Bind
. 关键字只需要
Bind
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.