July 11

On Monday, 11 July 2022 at 05:41:40 UTC, jfondren wrote:

>

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).

And you were right. I did search for a better solution and came across [1]. Although I was having some issues adapting it for my use case, Paul Backus' follow-up clarified the issue. This is what my naive brain led to before reading this response.

size_t[] shape(Variant v)
{
    typeof(return) dims;

    while(cast(TypeInfo_Array) v.type !is null) {
        dims ~= v.length;
        v = v[0];
    }

    if(!dims.length && v.length) {
        dims ~= v.length;
        dims ~= 0;
    }

    return dims;
}

Didn't see the bugs that would occur when a scalar or empty array was passed because I hadn't tested for them.

>
    if (!v.length) break;

Pure gold! Bugs are eliminated, and the code is shorter. Thank you.

--anonymouse

[1] https://tastyminerals.github.io/tasty-blog/dlang/2020/03/22/multidimensional_arrays_in_d.html

July 11

On Monday, 11 July 2022 at 06:59:32 UTC, anonymouse wrote:

>

I did search for a better solution and came across...
https://tastyminerals.github.io/tasty-blog/dlang/2020/03/22/multidimensional_arrays_in_d.html

I like it!

It's been a good collaboration...

import std.variant;

auto generate(T)(size_t x, size_t y) {
  T[][] result;
  ubyte[] arr = new ubyte[x * y * T.sizeof];
  size_t m = y * T.sizeof;

  foreach (i; 0 .. x) {
    size_t n = i * m;
    result ~= cast(T[])arr[n .. n + m];
  }
  return result;
}

size_t[] shape(Variant v) {
  typeof(return) dims;

  while (cast(TypeInfo_Array) v.type !is null) {
    dims ~= v.length;
    v = v[0];
  }

  if (!dims.length && v.length) {
    dims ~= v.length;
    dims ~= 0;
  }
  return dims;
}

void main() {
  foreach(x; 1..100) {
    foreach(y; 1..100) {
      auto test = Variant(generate!int(x, y));
      assert(shape(test) == [x, y]);
    }
  }
}

SDB@79

1 2
Next ›   Last »