Parameterized types and return values in D why does this not work?

135 Views Asked by At

OK, it seems my prior problem is now resolved (I've left it below for reference). However, yet another one crops up - again, seemingly something I'm missing. Further up in this code, I declared the following:

private:

T _data;
BinaryTree!(T) _left; 
BinaryTree!(T) _right;

Then after this, I declared these:

public:
@property T data() {return _data;}
@property BinaryTree!(T) left() {return _left;}
@property BinaryTree!(T) right() {return _right;}

Then, I implemented the following function:

void add (T data) {
    BinaryTree!(T) nearest = findNearest(this, data);
    if (nearest.data > data) {
        nearest.left = new BinaryTree!(T) (data);
    }
    else {
        nearest.right = new BinaryTree!(T) (data);
    }
}

The compiler is protesting that nearest.left and nearest.right aren't properties, although as nearest is a BinaryTree!(T), this seems rather odd. What am I missing?


OLD PROBLEM:

I've recently gotten into D, and was trying to build a binary tree implementation as a way of testing what I've learned by reading about it. Now, I started by declaring it as follows:

class BinaryTree(T)

I figured this would allow me to parametrize some of the stuff the class holds. More specifically:

T _data;
BinaryTree!(T) _left;
BinaryTree!(T) _right;

Now, I then tried writing this:

BinaryTree!(T) findNearest (BinaryTree(T) x, T key) {
    if (x.hasNoChildren || x.data == key) {
        return x; //found it
    }
    else {
        auto compare = x.data;
        if (compare > key) {
            return find (x.left, key);
        }
        else {
            return find (x.right, key);
        }
    }
}

After this, the compiler loudly complained about my function not having a return type. What am I doing wrong here? If it helps to explain, I come from a Java background, and I'm using the dmd compiler inside of Xamarin Studio.

1

There are 1 best solutions below

4
On BEST ANSWER

The only error I can see is a missing ! in the function parameter:

BinaryTree!(T) findNearest (BinaryTree(T) x, T key) {

should be

BinaryTree!(T) findNearest (BinaryTree!(T) x, T key) {

The rest looks fine to me.