tags:

views:

347

answers:

2
> seq { for i in 0..3 do yield float i };;
val it : seq<float> = seq [0.0; 1.0; 2.0; 3.0]
> seq [ for i in 0..3 do yield float i ];;
val it : seq<float> = [0.0; 1.0; 2.0; 3.0]

P.S. why did F# originally expect sequences without the "seq" prefix, but now they want the prefix?

+3  A: 

The first is a seq (IEnumerable).

The second is weird; get rid of the 'seq' and it's a list comprehension (list). There's no reason to write it as is; either use seq{ } or [ ] or [| |] to make a seq or a list or an array.

The curlies-not-prefixed-by-seq is a form that will be deprecated, as it makes some other parts of the language potentially ambiguous.

Brian
I'm too newbie to know the difference between the first and second forms. Would you mind clarifying?
Qwertie
The second form is really a list, as noted by the [ ]. seq just turns it into a sequence after it's been generated as a list.
MichaelGG
+5  A: 

More clarification on the two forms you posted:

The first one uses a direct sequence comprehension, "seq { ... }". The "seq" part was optional before, but that's not going to be supported in the future. I guess it makes things like "async { ... }" and the workflow syntax more difficult or something.

Now, the second one is a pure list:

> let x = [ for i in 0..3 do yield float i ];;

val x : float list

"seq" is also a function:

> seq;;
val it : (seq<'a> -> seq<'a>) = <fun:clo@0_1>

And since any list is also a sequence, doing "seq [1;2;3;]" is just applying the seq function to the list. It's sorta like casting it to seq from the list type.

> x;;
val it : float list = [0.0; 1.0; 2.0; 3.0]

> seq x;;
val it : seq<float> = [0.0; 1.0; 2.0; 3.0]

Edit: The source for the seq function is:

let seq (x : seq<_>) = (x :> seq<_>)

So, "sorta like casting it" should read "casting it via a helper function". As for the printing of sequences inside brackets, I think that's just a pretty printing artifact.

MichaelGG
It's confusing that the interpreter says that "seq { for i in 0..3 do yield float i };;" has a value of "seq [0.0; 1.0; 2.0; 3.0]", yet if you type "seq [0.0; 1.0; 2.0; 3.0];;" directly, the interpreter says it has a value of "[0.0; 1.0; 2.0; 3.0]".
Qwertie
Is applying the seq function "sort of" like casting to seq (=IEnumerable), or is it F#'s direct equivalent of a cast?
Qwertie
Or, does F# have a separate cast operator?
Qwertie
F#'s cast operators are :> for upcasts and :?> for downcasts.
MichaelGG