the best language I have ever met(?)
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Nov 25 06:51:52 PST 2016
On Friday, November 25, 2016 14:27:39 Igor Shirkalin via Digitalmars-d-learn
wrote:
> On Wednesday, 23 November 2016 at 18:58:55 UTC, ketmar wrote:
> >> We can define static array without counting the elements as
> >> following:
> >>
> >>
> >> enum array_ = [1u,2,3,4];
> >> uint[array_.length] static_array = array_;
> >
> > there are workarounds, of course. yet i'll take mine `uint[$] a
> > = [1u,2,3,4];` over that quoted mess at any time, without
> > second thought. ;-)
>
> I think you may write it (I mean actual D) with using some
> template like this:
>
> auto array = static_array!uint(1, 2, 3, 4)
>
> Could you please help to write down this template in the best and
> clear manner?
That's easy. The problem is if you want it to have the same semantics as
uint[4] arr = [1, 2, 3, 4];
In particular, VRP (Value Range Propagation) is a problem. This compiles
ubyte[4] arr = [1, 2, 3, 4];
because each of the arguments is known to fit in a ubyte. However, making
auto arr = staticArray!ubyte(1, 2, 3, 4);
do the same without forcing a cast is difficult. And if you force the cast,
then it's not equivalent anymore, because something like
ubyte[4] arr = [1, 2, 3, 900];
would not compile. And surprisingly, having the function take a dynamic
array doesn't fix that problem (though maybe that's something that we could
talk the dmd devs into improving). e.g.
auto arr = staticArray!ubyte([1, 2, 3, 4]);
doesn't compile either. The most straightforward implementations are
something like
T[n] staticArray(T, size_t n)(auto ref T[n] arr)
{
return arr;
}
or
auto staticArray(Args...)(Args args)
{
CommonType!Args[Args.length] arr = [args];
return arr;
}
but I don't know if the VRP problem is solvable or not without some compiler
improvements. If there's a clever enough implementation to get VRP with a
function like this with the current language, I haven't figured it out yet.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list