Polymorphic recursive class

Dmitry Olshansky via Digitalmars-d digitalmars-d at puremagic.com
Mon Jul 13 06:51:43 PDT 2015


On 13-Jul-2015 16:15, Jack Applegame wrote:
> On Monday, 13 July 2015 at 12:53:12 UTC, deadalnix wrote:
>> On Monday, 13 July 2015 at 11:36:48 UTC, Jack Applegame wrote:
>>> Yes, that is I intended.
>>> It is a pretty useless example, just for demonstrating the lack of
>>> support polymorphic recursive data types.
>>
>> So the point is that we should add feature to the language to support
>> useless use cases ?
>
> Not all cases are useless. For example, typical functional programming
> patterns like recursive compile-time trees and lists.

You can do it no problem, it just requires to manually implement boxing 
and make `right` a template that casts to the right type. The reason is 
that D doesn't provide an extra abstraction layer that is 
"auto-magically" there in typical FP language.

Not tested but this should work:

class Nested(T){
	T left;
	void* right_; // or use opaque type if allergic to void*
	@property auto right()(){ // empty template to prevent recursion
		return cast(Nested!(T[])right_;
	}
	@property auto right(U)(Nested!U type){ // empty template to prevent 
recursion
		right_ =  cast(void*)right_;
	}
	
	// and lastly the constructor should be templated
	this(U)(T l, Nested!(U) r) {
    	 left = l;
    	 right = r;
   	}
}

-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list