How to obtain Variant underlying type?

jfondren julian.fondren at gmail.com
Mon Jul 11 05:41:40 UTC 2022


On Monday, 11 July 2022 at 03:17:33 UTC, anonymouse wrote:
> On Sunday, 10 July 2022 at 18:31:46 UTC, drug007 wrote:
>>
>> I'd like to say that using of exception to break loop is 
>> really bad. Exception is exceptional thing but in the case 
>> above the exception is ordinary completion of the loop happens 
>> on regular basis. Don't do that.
>
> Thanks for the advice. Lesson learned.
>
> --anonymouse

Oh, sorry. I didn't defend the code in any way because I assumed 
that the exceptional design would be seen as obviously bad (and 
that someone else would dig harder in order to find a better 
solution).

The TypeInfo_Array fix breaks the last assertion of those unit 
tests, though. This works:

```d
import std.variant : Variant;

size_t[] shape(Variant v) {
     size_t[] s;
     while (cast(TypeInfo_Array) v.type !is null && v.length > 0) {
         Variant elem = v[0];
         s ~= v.length;
         v = elem;
     }
     return s;
}
```

Although, that last assertion really is debatable. Languages like 
APL would read it as having a shape of [2, 0]:

```d
import std.variant : Variant;

size_t[] shape(Variant v) {
     size_t[] s;
     while (cast(TypeInfo_Array) v.type !is null) {
         s ~= v.length;
         if (!v.length) break;
         v = v[0];
     }
     return s;
}

unittest {
     assert([3, 1] == [[1], [2], [3]].Variant.shape);
     assert([2, 1] == [[1], [2]].Variant.shape);
     assert([2, 2] == [[1, 0], [2, 0]].Variant.shape);
     assert([2] == [1, 2].Variant.shape);
     assert([] == 2.Variant.shape);
     assert([2, 0] == [[], []].Variant.shape);

     // irregularity not checked
     assert([2, 2] == [[1, 0], [2]].Variant.shape);
}
```


More information about the Digitalmars-d-learn mailing list