Type system question

Bill Baxter wbaxter at gmail.com
Wed Dec 10 17:17:54 PST 2008


On Thu, Dec 11, 2008 at 9:44 AM, BCS <ao at pathlink.com> wrote:
> Reply to bearophile,
>
>> Tim M:
>>
>>> How would that improve on auto?
>>>
>> It's like asking how a domestic Flying Disk UFO can improve your
>> bicycle travels to the nearby milk shop :-)
>>
>> The answer is: it can do that and much more.
>>
>> Bye,
>> bearophile
>
> C++ template are Turing compleat -> D template probably are. What more do
> you want?

CPU instructions typed in binary is Turing complete too.  What more do we need?

Seriously though, here's an example taken from the wikipedia "Type
Inference" page

someFunction(x, y) {
    return x+y;
}

addone(x) {
    val result;  /*inferred-type result (in proposed language)*/
    result = someFunction(x,1);
    return result;
}

With full type inference, the compiler knows that addone takes an int
and returns an int.
How?
- Because + only adds values of the same type
- Therefore someFunction takes two values of the same type
- addone calls someFunction with x and an int.  Since someFunction
takes two values of the same type, x must be an int too.
- finally some function returns the same type as its inputs, so
'result' is also an int.
- therefore addone is a function that takes an int and returns an int.

And all that was determined by the fact that an integer literal was
used somewhere in the middle of the function.

Now, whether all this is really a good thing or not I'm not sure.
With my code maintainer's hat on it seems very hard to see that addone
expects an int.  But usually functions in languages with uber type
inference are written a little more generically and don't have a
literal integer '1' sitting there, killing the generality for no good
reason.  :-)

So what D has is basically the ability to do type inferences in one
direction.  If you say auto x = somefun(y), it expects the RHS to to
have a well-defined type.  But with full type inference you can
basically have auto anywhere and it can infer it from what happens
somewhere after that point in the code.

T[] something(T)(T x) {  return [x]; }
void getValue(ref int v) { v = 1; }
void getValue(ref string v) { v = "one"; }

....
auto a;
getValue(a);
int[] x = something(a);

there it knows 'a' has to be an int because that's the only thing that
is consistent.


--bb



More information about the Digitalmars-d mailing list