Difference between Seq and Array for array value
I'm quite new in F#.
I guess arrays are still collections, so I could use Seq
for iterating the array like this:
[|"a"; "b"|] |> Seq.map (fun f -> printfn "a") |> ignore;;
But that doesn't work - it prints nothing.
On the other hand if I use Array
, it prints the strings:
[|"a"; "b"|] |> Array.map (fun f -> printfn "a") |> i开发者_JAVA百科gnore;;
Why is that?
Array.map
builds another array - which means it has to do it eagerly. You can't build an array and say "I'll fill in the values when you want them."
Sequences, on the other hand, are evaluated lazily... it's only when you ask for the values within the result sequence that the mapping will be evaluated. As stated in the documentation for Seq.map
:
The given function will be applied as elements are demanded using the MoveNext method on enumerators retrieved from the object.
If you're familiar with LINQ, it's basically the difference between Enumerable.Select
(lazily producing a sequence) and Array.ConvertAll
(eagerly projecting an array).
Neither of these are the way to iterate over an array or a sequence though - they're projections. As Stringer Bell says, Array.iter
and Seq.iter
are the appropriate functions for iteration.
You have to use Seq.iter
if you want to iterate on your collection, just like that:
[|"a"; "b"|] |> Seq.iter (fun f -> printfn "%A" f);;
Also you can just use Array.iter
, if only iterating on arrays:
[|"a"; "b"|] |> Array.iter (fun f -> printfn "%A" f);;
Another (and shorter) alternative is directly piping your value into printfn "%A"
function:
[|"a"; "b"|] |> printfn "%A";;
will print [|"a"; "b"|]
. Note that in this case F# prints it exactly like you would have coded it.
精彩评论