[swift-evolution] [Pitch] New collection-based 'repeat' API
Karl Wagner
razielim at gmail.com
Mon May 1 21:34:40 CDT 2017
Currently, we have the Repeated<T> type, which presents a single element as though it were a Collection.
> for i in repeatElement(1, count: 3) { print(i) }
1
1
1
> for i in repeatElement([1, 2, 3], count: 3) { print(i) }
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
However, we lack the ability for Collections to repeat their contents in a single list; basically, some kind of “flatMap” to repeatElement’s “map”. So I’d like to pitch a new API for repeated values.
- We would add a RepeatCollection<C: Collection> type, which loops over its base Collection a certain number of times (or until a maximum ‘count’).
Implementation might look something like this (https://gist.github.com/karwa/5228974a0b4dfd000a916f0aac2721c6), except that we’d add some optimised map(), filter() and contains() functions which apply the algorithm once to the base and multiply the result.
- We would add 3 new functions to all Collections:
/// Repeats the collection itself N times.
///
func repeated(_ times: Int) -> RepeatCollection<CollectionOfOne<Self>>
/// Repeats the collection’s contents N times.
///
func repeatElements(_ times: Int) -> RepeatCollection<Self>
/// Loops the collection’s contents to present a Collection of length N.
///
func repeatElements(count: Int) -> RepeatCollection<Self>
- We would replace the existing Repeated<T> type with a typealias to RepeatCollection<CollectionOfOne<T>>
- The existing, top-level repeatElement(T, Int) function could stay, but could also be replaced with an incantation on CollectionOfOne. I’m fairly ambivalent about this point - it’d be nice to see the function go, but the replacement also isn’t obvious.
Example usage of the new API:
// Equivalent to repeatElement(1, count: 3)
> for i in CollectionOfOne(1).repeatElements(3).forEach { print(i) }
1
1
1
// Equivalent to repeatElement([1, 2, 3], count: 3)
> for i in [1, 2, 3].repeated(3).forEach { print(i) }
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
// New, flat repetition
> for i in [1, 2, 3].repeatElements(3) { print(i) }
1
2
3
1
2
3
1
2
3
// New, flat repetition
> for i in [1, 2, 3].repeatElements(count: 4) { print(i) }
1
2
3
1
// Additional benefit: you can now repeat slices!
> String(“yellow”.characters.dropFirst().dropLast().repeat(times: 3))
“elloelloello"
Thoughts?
- Karl
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170502/ca2aaaa8/attachment.html>
More information about the swift-evolution
mailing list