Why does F#'s Seq.windowed return seq of array
f#
Solution
I do not know what is the design principle behind this. I suppose it might just be an accidental aspect of the implementation - `Seq.windowed` can be quite easily implemented by storing items in arrays, while `Seq.groupBy` probably needs to use some more complicated structure.
In general, I think that F# APIs either use `'T[]` if using array is the natural efficient implementation, or return `seq<'T>` when the data source may be infinite, lazy, or when the implementation would have to convert the data to an array explicitly (then this can be left to the caller).
For `Seq.windowed`, I think that array makes a good sense, because you know the length of the array and so you are likely to use indexing. For example, assuming that `prices` is a sequence of date-price tuples (`seq<DateTime * float>`) you can write:
prices
|> Seq.windowed 5
|> Seq.map (fun win -> fst (win.[2]), Seq.averageBy snd win)
The sample calculates floating average and uses indexing to get the date in the middle.
In summary, I do not really have a good explanation for the design rationale, but I'm quite happy with the choices made - they seem to work really well with the usual use cases for the functions.
Problem
`Seq.windowed` in F# returns a sequence where each window within is an array. Is there a reason why each window is returned as an array (a very concrete type) as opposed to say, another sequence or `IList<'T>`? An `IList<'T>`, for example, would be sufficient if the purpose was to communicate that the items of the window can be randomly accessed but an array says two things: elements are mutable and randomly accessible. If you can rationalise the choice of array, how is `windowed` different from `Seq.groupBy`? Why does that latter (or operators in the same vein) not also return the members of a group as an array? I'm wondering if this is simply a design oversight or is there a deeper, contractual reason for an array?