How do you flatten a Sequence of Sequences in Ceylon?
ceylon, sequence
Solution
The variadic function `concatenate()` concatenates iterables, producing a sequence:
Integer[] prod(Integer max, Integer occurrences) {
Integer[][] nestedSequence = [ for (occurrence in 1..occurrences) range(max) ];
return concatenate(*nestedSequence);
}
This can be rewritten less verbosely like this:
Integer[] prod(Integer max, Integer occurrences)
=> concatenate(for (occurrence in 1..occurrences) range(max));
But I don't like this implementation because it does lots of eager instantiation of sequences. I would much prefer this implementation, which only does one sequence instantiation:
Integer[] prod4(Integer max, Integer occurrences)
=> [ for (occurrence in 1..occurrences) for (x in range(max)) x ];
FYI, in Ceylon 1.1, the `expand()` function has been added which is lazier than `concatenate()`.
HTH, good luck!
Problem
Given a type that is a Sequence of Sequences, how do I convert it to a single, flattened Sequence type? Consider the following Ceylon code: ``` Integer[] range(Integer max) { return [ for (idx in 1..max) idx ]; } Integer[] prod(Integer max, Integer occurrences) { Integer[][] nestedSequence = [for (occurrence in 1..occurrences) range(max)]; return // ??? something to produce a flattened sequence } assert (prod(2, 2) == [1, 2, 1, 2]); ``` I'm experimenting with Ceylon for the first time and fumbling my way through the tutorials and API documentation. The unzip method looks somewhat close to what I need, but not exactly.