Complex numbers are harder to use than in C

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Nov 20 03:58:09 PST 2016


On Saturday, 19 November 2016 at 20:24:09 UTC, Marduk wrote:
> On Saturday, 19 November 2016 at 12:55:57 UTC, Marc Schütz 
> wrote:
>> On Saturday, 19 November 2016 at 11:11:36 UTC, Nordlöw wrote:
>>> On Saturday, 19 November 2016 at 09:38:38 UTC, Marduk wrote:
>>>> The difference is that D is more verbose. Am I missing 
>>>> something? Can we have C's behaviour in D?
>>>
>>> Something like
>>>
>>> auto I(T)(T im)
>>>     if (isNumeric!T)
>>> {
>>>     return complex(0, im);
>>> }
>>>
>>> unittest
>>> {
>>>     auto x = 1 + 2.I;
>>> }
>>
>> Or simply:
>>
>> enum I = complex(0, 1);
>> auto x = 1 + 2*I;
>
> Thanks! That's a clever idea.
>
> What I do not understand is why if I declare the array with 
> Complex!double I need to complexify each entry. I would expect 
> that D automatically casts 0.0 to complex(0.0).

I agree, this is unfortunate. I don't know of any reason why the 
following couldn't work in principle:

Complex!float[] arr = [1.0, 2.0, 3.0, 4.0];
// or even
auto arr = [1+2*I, 2.0, 3.0, 4.0];    // compiler finds common 
type
// just like it works for
auto arr = [1, 2, 3.0, 4];    // typeof(arr) is double[]

I believe it was a conscious decision. D doesn't do as many 
implicit type conversion as C++, because they often make it hard 
to understand what's going on. In the above examples though, IMO 
it wouldn't be a problem.


More information about the Digitalmars-d-learn mailing list