Custom indexing

My friend Stefano @ste is really enthusiastic about Swift, but he doesn’t love the 0..<5 range syntax - it’s hard to type and not very concise. He prefers Python’s :5 colon indexing. Unfortunately the : character is not allowed for custom operators in Swift, so I wrote this silly snippet for him using | instead:

prefix operator |
prefix func |(n: Int) -> Range<Int> {
    return 0..<n
}

Therefore if you have a Tensor like so:

var t = Tensor<Float>(randomNormal: TensorShape(5, 4))
t
[[ -0.6274641,  -0.5159432, -0.37829402,  0.56560385],
 [-0.70372456, -0.43395498,   0.5455911,  -1.3490856],
 [  2.3749003, -0.68107045,   0.5483691, -0.18535607],
 [  0.6491169,  -0.1704834,  -0.1894283,   0.2739358],
 [ -1.1265595, -0.17301613,  -1.1592884,  0.92231935]]

You can do:

t[|1]
[[ -0.6274641, -0.5159432, -0.37829402, 0.56560385]]

t[|1,|2]
[[-0.6274641, -0.5159432]]

This is just an example with many limitations, but I suppose it could be extended to better support a somewhat more expressive syntax if anyone wants to do so :slight_smile:

4 Likes

Thant’s Great! Thank you Pedro :wink:

1 Like

You can use partial ranges.

tensor[..<n]
3 Likes

I would say that these pipes characters make the indexation syntax a bit harder to read, especially if you have many of them.

It would be nice to get Python’s indexing in Swift, especially allowing for negative indices and strides. Currently you have to write:

for i in stride(from: n - 1, through: 0, by: -1) { ... }

It would be nicer if there was syntactic sugar shorthand for this.

3 Likes