[swift-evolution] Yet another fixed-size array spitball session
Haravikk
swift-evolution at haravikk.me
Thu Jun 1 06:36:07 CDT 2017
Just wanted to add my two-cents to this discussion, but in terms of syntax I think that the basic method for specifying size should be with some kind of type variables, like so:
struct MyFixedArray<T, size:Int> { … }
The idea being that we can then use size as a variable anywhere within the code for MyFixedArray, but unlike other variables it is determined at compile time, so should be optimised accordingly. As with generics, setting a type variable effectively creates a variant type so for example, a MyFixedArray<Int, size:3> and a MyFixedArray<Int, size:4> would no longer be directly compatible as they may differ internally.
This would be useful not just for fixed arrays, but other possibly type variations as well. Ideally it should be possible to specify a default value for type variables; while this wouldn't be useful for fixed arrays, it may be useful for other type variants.
To better suit the specific use-case of arrays, we could also add some useful attributes or keywords, for example, reusing subscript could give us:
struct MyFixedArray<T, subscript size:Int> { … }
let foo:MyFixedArray[4] = [1, 2, 3, 4] // with T being inferred, this is a shorthand for specifying a size of 4
Type variables could also be usable with generics, like-so:
// only accept fixed arrays of same or smaller size:
func myMethod<FA>(values:FA) where FA:FixedArray, FA.size <= Self.size { … }
These are the kind of general purpose capabilities I'd like to see at some point, as the usefulness extends beyond just fixed-size arrays.
However, on the subject of fixed-size arrays specifically, one other possibility to explore is the concept of Tuple repetition and subscripting. For example, it would be interesting if we could do things like:
var foo:(Int)[4] = 0 // Initialises four Ints, all set initially to zero
for i in 0 ..< 4 { foo[i] = i } // values are no 0, 1, 2, 3
This can be especially interesting when you get into more complex tuples like so:
var bar:(x:Int, y:Int)[10] = (x: 0, y: 0) // Initialises 10 pairs of Ints, all initially set to zero
for i in 0 ..< 10 { bar[i].x = i; bar[i].y = i } // here we need to use .x and .y to access the values of each pair
Of course this would have the same performance characteristics as standard tuples, but it's an interesting means for creating quick, fixed-size arrays in a flexible way. Part of the idea here is that by subscripting tuples, we avoid the need for a general subscript on all types, keeping that available for use-cases like the above.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170601/717bcca3/attachment.html>
More information about the swift-evolution
mailing list