spir:

> What is the common idiom to check whether the type of a given element is what 
> I expect?
> Seems that
>       typeof(e) == Type
> is refused by the compiler, for any reason? I get
>       DeeMatch.d(237): Error: type string is not an expression

I don't know why the language refuses a natural and more clean syntax like:
if (typeof(x) == Type) {...
I think it's to keep the compiler simple, clearly telling apart the 
compile-time phase that uses types (or CTFE) from the run-time that uses values.
So you have to wrap it into a is(), often this is enough:
if (is(typeof(x) == Type)) {...
But look in the docs at the complex syntax of is() for the many other different 
ways to use it.


> Also, how to override a class's field so that it is accessed according 
> actual/runtime type? (Like method dispatch.)

This feature is named "double dispatch", and it's present in the object system 
named CLOS of CommonLisp, but unfortunately it's not present in D (or C++, 
Java, Python). Maybe the Scala language too has this feature. See:
http://en.wikipedia.org/wiki/Double_dispatch
http://en.wikipedia.org/wiki/Visitor_pattern

The D language allows you to perform the dispatch only on the compile time type 
of the arguments (or the dynamic type of the "this"). This means that if you 
have to perform double dispatch in D/C++/Python, then you need to 
implement/simulate this feature manually. There are several ways to do it, see 
. In some situations if your program needs to use double dispatch heavily, then 
you may invent a string mixin to reduce somehow the boilerplate code.


>       void method (SuperType x) {...access x.f...}
> If I don't define f in SuperType, then I get a compiler error. If I do, then 
> SuperType.f is accessed, not the field on actual class of x.

D is a statically typed language, this means that in general the choices about 
types (this mean choice of code path or code generation by templates) are 
performed only at compile time.

Despite languages like Java and D are statically typed, they allow a bit of 
dynamic typing, using the virtual table of the classes, and allowing run-time 
types of objects to differ from their compile-time type. But this bit of 
dynamic typing is limited and is not extended to double/multiple dispatch (on 
the other hand even very dynamic languages like Python lack double or multiple 
dispatch).

Bye,
bearophile

Reply via email to