nested &defaults

Hello again,

I have a record with a field like this:

type Histogram: record {
  histogram: vector of count;
};

I'd like histogram field to default to an empty vector and the
individual counts in the vector to default to 0. I.e., I want the below
code to print "42".

global foo: Histogram;
foo$histogram[5] += 42;
print(foo$histogram[5]);

Is that possible to set defaults for both $histogram and $histogram[N]?

I didn't think vectors supported a &default attribute very well, so I didn't try too hard to make that work, but here's what I came up with using a table indexed by counts and yielding counts (which is pretty much equivalent to a vector of count):

    type HistogramType: table[count] of count;

    function histogram_default(index: count): count
        {
        return 0;
        }

    const new_histogram: HistogramType = table() &default=histogram_default;

    type HistogramRecord: record {
        histogram: HistogramType &default=copy(new_histogram);
        other_stuff: string &optional;
    };

    global foo: HistogramRecord;
    global foo2: HistogramRecord;

    foo$histogram[5] += 42;
    print(foo$histogram[5]);
    foo2$histogram[5] += 13;
    print(foo2$histogram[5]);

The big trick there is that attributes don't currently propagate from types to values, so instead of setting a &default function on the HistogramType, I had to apply it to a constant, empty table and clone that for every new histogram instance.

- Jon

Thanks, that works! One question below, though:

Why not just do &default=0 instead of histogram_default? That works for
me.

I was only playing around to verify what I could get to work. Since you don't need the default value to be a function of the index, &default=0 is fine.

- Jon