简体   繁体   English

数组值的Seq和Array之间的差异

[英]Difference between Seq and Array for array value

I'm quite new in F#. 我是F#的新手。

I guess arrays are still collections, so I could use Seq for iterating the array like this: 我猜数组仍然是集合,所以我可以使用Seq迭代数组,如下所示:

[|"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: 另一方面,如果我使用Array ,它会打印字符串:

[|"a"; "b"|] |> Array.map (fun f -> printfn "a") |> ignore;;

Why is that? 这是为什么?

Array.map builds another array - which means it has to do it eagerly. Array.map构建另一个数组 - 这意味着它必须急切地执行它。 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 : Seq.map的文档中Seq.map

The given function will be applied as elements are demanded using the MoveNext method on enumerators retrieved from the object. 在从对象检索的枚举数中使用MoveNext方法需要元素时,将应用给定的函数。

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). 如果您熟悉LINQ,那么它基本上就是Enumerable.Select (懒洋洋地生成序列)和Array.ConvertAll (急切地投射数组)之间的区别。

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. 正如Stringer Bell所说, Array.iterSeq.iter是迭代的合适函数。

You have to use Seq.iter if you want to iterate on your collection, just like that: 如果你想迭代你的集合,你必须使用Seq.iter ,就像那样:

[|"a"; "b"|] |> Seq.iter (fun f -> printfn "%A" f);;

Also you can just use Array.iter , if only iterating on arrays: 如果只迭代数组,你也可以使用Array.iter

[|"a"; "b"|] |> Array.iter (fun f -> printfn "%A" f);;

Another (and shorter) alternative is directly piping your value into printfn "%A" function: 另一个(和更短的)替代方案是直接将您的值输入printfn "%A"函数:

[|"a"; "b"|] |> printfn "%A";;

will print [|"a"; "b"|] 将打印[|"a"; "b"|] [|"a"; "b"|] . [|"a"; "b"|] Note that in this case F# prints it exactly like you would have coded it. 请注意,在这种情况下,F#打印它就像您编写它一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM