[英]what is the difference between '->' and 'do' in a for loop, in F#
I can do this:我可以做这个:
[ for i in 0 .. 5 -> i ]
or或者
[ for i in 0 .. 5 do i ]
but, while I can do this:但是,虽然我可以这样做:
[ for i in 0 .. 5 do yield! [i * 4; i] ]
I can't do that:我不能这样做:
[ for i in 0 .. 5 -> yield! [i * 4; i] ]
why is that?这是为什么? how are the two treated differently?
两者如何区别对待?
This is quite tricky, because there are a few things here that F# does implicitly.这很棘手,因为 F# 隐含地做了一些事情。
First, the ->
syntax is really just a shortcut for do yield
, so the following translates as:首先,
->
语法实际上只是do yield
的一种快捷方式,因此以下翻译为:
[ for i in 0 .. 5 -> i ]
= [ for i in 0 .. 5 do yield i ]
This explains why you cannot do -> yield!
这就解释了为什么你不能做
-> yield!
because the translation would result in:因为翻译会导致:
[ for i in 0 .. 5 -> yield! [i * 4; i] ]
= [ for i in 0 .. 5 do yield (yield! [i * 4; i]) ]
You would have yield!
你会有
yield!
nested inside yield
, which makes no sense.嵌套在
yield
中,这没有任何意义。
The second tricky thing is the syntax with just do
.第二个棘手的问题是 just
do
的语法。 This is a recent change in F# that makes writing list generators easier (which is fantastic for domain-specific languages that construct things like HTML trees) - the compiler implicitly inserts yield
so the code translates as:这是 F# 中的最新更改,它使编写列表生成器变得更容易(这对于构造诸如 HTML 树之类的特定领域的语言来说非常棒) - 编译器隐式插入
yield
,因此代码转换为:
[ for i in 0 .. 5 do i ]
= [ for i in 0 .. 5 do yield i ]
The interesting thing is that this works with multiple yields as well:有趣的是,这也适用于多个产量:
[ for i in 0 .. 5 do
i
i*10 ]
= [ for i in 0 .. 5 do
yield i
yield i*10 ]
This is another difference between ->
and do
.这是
->
和do
之间的另一个区别。 With ->
, you can only yield one thing.使用
->
,您只能产生一件事。 With do
, you can yield multiple things.使用
do
,你可以产生多个东西。
I imagine that there is very little reason for using ->
nowadays.我想现在几乎没有理由使用
->
了。 This was in the language before the implicit yield
and so it was useful in earlier versions of F#.这是隐式
yield
之前的语言,因此在 F# 的早期版本中很有用。 You probably do not really need that anymore when do
makes things as easy.当
do
让事情变得如此简单时,您可能不再需要它了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.