www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why D functions paramter can not implicit infer type of Variant?

reply Marcone <marcone email.com> writes:
import std;

void a(int b){
}

void main()
{
   Variant c = 10;
   a(c); // Error
}

Need more sugar.
Jan 13 2021
next sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 1/13/21 8:17 AM, Marcone wrote:

 import std;

 void a(int b){
 }

 void main()
 {
    Variant c = 10;
    a(c); // Error
 }

 Need more sugar.
That can't work in a strongly statically typed language. The call a(c) is decided at compile time but Variant is not an int at compile time. It could only work if Variant were a user-defined type that had an automatic conversion to int with 'alias this'. Ali
Jan 13 2021
prev sibling parent reply sighoya <sighoya gmail.com> writes:
On Wednesday, 13 January 2021 at 16:17:02 UTC, Marcone wrote:
 import std;

 void a(int b){
 }

 void main()
 {
   Variant c = 10;
   a(c); // Error
 }

 Need more sugar.
Two problems: 1.) Variant is library defined, compared to the language level there isn't a default strategy to choose int32 here, it could be also, short, long, unsigned ... not to mention all the alias this types. Though it may be possible to define a default strategy but part of the problem is how to tell D to init the type parameters appropriately. 2.) c is mutable, what is if you return c and assign other values of other types to it? Determining all possibilities by traversing following assignments leads to global type inference which no one would ever want to have especially with support of subtyping. A more natural conclusion would be to infer c to the most common supertype as other inferences would unnecessarily exclude future assignments to c. But the most common supertype doesn't seem to exist, and I'm unsure if this type can be modeled at all in D?
Jan 13 2021
parent reply Paul Backus <snarwin gmail.com> writes:
On Wednesday, 13 January 2021 at 18:09:08 UTC, sighoya wrote:
 A more natural conclusion would be to infer c to the most 
 common supertype as other inferences would unnecessarily 
 exclude future assignments to c.  But the most common supertype 
 doesn't seem to exist, and I'm unsure if this type can be 
 modeled at all in D?
That's what Variant is--a struct that models the universal supertype (sometimes called "Top" or "Any").
Jan 13 2021
parent sighoya <sighoya gmail.com> writes:
On Wednesday, 13 January 2021 at 19:38:55 UTC, Paul Backus wrote:

 That's what Variant is--a struct that models the universal 
 supertype (sometimes called "Top" or "Any").
Ahh right. Good point, so it already fits.
Jan 13 2021