[swift-evolution] [Pitch] #dup -- a duplication "macro"(?)

Daryle Walker darylew at mac.com
Mon Jul 31 21:23:16 CDT 2017

When coming up with new array interfaces, I had some array to/from tuple conversion functions:

func array<T, U…>(from: (T, …U)) -> [1 + #countOf(U) ; T] allwhere U == T

The problem is going the other way:

func tuple<T, N: Int>(from: [N; T]) -> ???

The tuple will be a bunch of “T,” but the count mechanically added depends on compiler-visible number N. Well, since this is part of a proposal that already mutates the language, I thought why not add a primitive operation by fiat:

func tuple<T, N: Int>(from: [N; T]) -> ( #dup(N; T) )

where “#dup” dumps a comma-separated list repeating the right-side entity with a multiplicity of the left-side value. The left-side value has to be a compiler constant expression. I was going to have the right side be an arbitrary token sequence, but I think it’s better for now to limit it to either a type (or similar) or an expression. Obviously, the receiver has to compatible with whatever being dumped there.


Could we do better than simple repetition? What if we define a “$$n” unit, where “n” is a nonnegative integer. For each comma-separated item, the unit will be replaced by increasing compiler-constant integers from zero. If using an expression, maybe you can call a function on the double-dollar value to get your own custom values there. This can be expanded to types once value-based generic parameters get added.

When there are nested #dup calls, the double-dollar unit refers to the counter for the innermost #dup. Maybe there can be a triple-dollar unit for the immediately enclosing #dup. Even quadruple- or more-dollar units for the outer levels. (Hopefully, nothing more that one level would be needed.)


Later, I remembered the "( 6 * TupleMemberType )” syntax for repeating a type within a tuple that's sometimes suggested. The #dup facility can be seen as a generalized version of that quasi-array-specific idea.

Daryle Walker
Mac, Internet, and Video Game Junkie
darylew AT mac DOT com 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170731/7a2aa4af/attachment.html>

More information about the swift-evolution mailing list