Hello, folks! Newbie to D, have some questions!
timmyjose via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Feb 20 07:21:37 PST 2017
On Monday, 20 February 2017 at 14:54:58 UTC, Adam D. Ruppe wrote:
> On Monday, 20 February 2017 at 14:44:41 UTC, timmyjose wrote:
>> My confusion is this - the declaration of the array is arr
>> [last-dimension]...[first-dimension], but the usage is
>> arr[first-dimension]...[last-dimension]. Am I missing
>> something here?
>
> I've never understood how anyone could actually like C's weird,
> backward way of doing arrays. It never made a lick of sense to
> me.
Hahaha! I suppose it's just a question of ingrained habit! :-)
> D is beautifully consistent: each index "peels off" a layer. If
> you had a function returning a function:
>
> void function(string) foo() {
> return (string name) { writeln("hi, ", name); };
> }
>
> Is a zero-arg function that returns a function that takes a
> string parameter.
>
> How would you call the returned function?
>
> foo("adam")()
>
> or
>
> foo()("adam")
>
> ?
>
>
> Of course, the answer is the second form: the first level of ()
> calls the function `foo`, which returns the function that takes
> the string parameter.
>
>
>
> Arrays are the same thing.
>
> int[2][3] arr;
>
> is a 3-element array of 2-element arrays of int. So, how do you
> get to the int[2]? You peel away a level of []:
>
> int[2] row = arr[0] // that peels away the [3], leaving an
> int[2]
>
> int a = row[0]; // peel away the last level, leaving just int
>
>
Yes, this does make sense!
> Beautifully consistent, even if you want pointers:
>
> int[2]*[3] arrOfPointers;
>
> arrOfPointers[0] // type int[2]*, aka "pointer to two-element
> array of int"
>
>
>
> And once you realize that opIndex can be overloaded, it makes
> even more sense:
>
>
> arr[1][0] gets rewritten to arr.opIndex(1).opIndex(0) -
> bringing us back to my first example, we almost literally have
> a function returning a function again. Of course it reads the
> other direction from declaration!
Okay, I don't understand all of it, but I can see your argument
that it is more logically consistent this way.
More information about the Digitalmars-d-learn
mailing list