Hacker News new | ask | show | jobs
by sesuximo 2011 days ago
Imo foo[x][y] is better for many reasons:

- compiler can break it apart so foo[x] is evaluated once for many ys just like any other function

- you can make types that are unaware of their rank eg vector doesn’t know if it’s a 1D vector of int or a 2D vector of vectors

- “seamlessly” handles jagged arrays

4 comments

Which reminds me of an insightful observation that the array indexing operator [] and the function call operator () are basically doing the same thing: evaluating a function and returning a value.

So what you've just described is basically Currying, or partial function evaluation. It's a bit like defining "al(i)" as array lookup for an index 'i' instead of "[i]". Then the following are equivalent:

    something[i][j]
    something.al(i).al(j)
What people also want are:

    something[i,j]
    something.al(i,j)
In languages like Haskell, every function can always be evaluated argument-by-argument, with no special effort by the programmer. The compiler takes care of generating the code for the various intermediate call forms. In languages like C++, it would be a significant hassle to create all of the various partially-evaluated wrapper types.
In C++ you can create a simple generic reusable currying wrapper. Boost as a few. The reality is that the vast majority of C++ programmers don't see the need.
Trying to do this this through Currying turns a simple 2D array access into a quite complicated operation. One that a compiler has to be really smart to turn into a gheap 2D array indexing operation again. This really matters in number-crunching code, where it seems that almost everything is about multiplying arrays.
Of course it wouldn't make much sense to do it for indexing. I was discussing currying as a generally useful tool.
It's not the same when you support slicing. foo[x:y][z] is not the same as foo[x:y,z]. I'm not sure anyone is proposing slicing to be supported with the indexing operator in C++, though, so it might not matter.
It's semantically the same and the compiler should know that. But I do agree [][] makes more sense. The jth index of the ith array.
They'd probably be lowered to exactly the same code, so the compiler argument isn't very good.
If the user has access to both indices, they can make partially hosting harder/impossible