Why was "->" deprecated in F# comprehensions?
Sometimes in books I see this syntax for list and sequence comprehensions in F#:
seq { for i = 0 to System.Int32.MaxValue -> i }
This is from Programming F# by Chris Smith, page 80. In the F# which comes with VS2010, this doesn't compile. I believe ->
has been deprecated. (See Alternative List Comprehension Syntax). However, ->
can still be used in comprehensions which involve ranges:开发者_JAVA百科
seq { for c in 'A' .. 'Z' -> c }
According to Expert F# 2.0, page 58, this is because ->
is shorthand for Seq.map
over a range.
- Why was the first usage of
->
above deprecated? - The current use of
->
seems inconsistent. Can anyone reconcile this for me?
The ->
construct is supported only in the "simple" sequence expression syntax where you're doing a projection (Seq.map
) over some data source using the following structure:
seq { for <binding> in <input> -> <projection> }
The first example you mentioned is using for .. to ..
which is a different syntactical construct than for .. in
, but you can rewrite it using the second one (In fact, I almost always use for .. in
when writing sequence expressions):
seq { for i in 0 .. System.Int32.MaxValue -> i }
In all other forms of sequence expressions you'll have to use yield
. In earlier versions of F#, the ->
syntax was equivalent to yield
(and there was also ->>
which was equivalent to yield!
). So for example, you was able to write:
seq { -> 10 // You need 'yield' here
->> [ 1; 2; 3 ] } // You need 'yield!' here
This syntax looks quite odd, so I think that the main reason for making these two deprecated is to keep the language consistent. The same computation expression syntax is used in sequence expressions (where ->
makes some sense), but also for other computation types (and you can define your own), where yield
feels more appropriate (and it also corresponds to return
in asynchronous workflows or other computation expressions).
The "simple" sequence-specific syntax is still useful, because it saves you some typing (you replace do yield
with just ->
), but in more complicated cases, you don't save that many characters and I think that the syntax using ->
& ->>
can look a bit cryptic.
精彩评论