dave
dave

Reputation: 12806

Tail call optimization throwing error on simple function

I have a simple method to build a tree:

    @tailrec final def buildTree (X:DenseMatrix[Double], Y:DenseVector[Double], minBucket:Int):Node = {
        // Get the split variable, split point and data 
        val (splitVar, splitPoint, leftX, leftY, rightX, rightY) = chooseSplit(X, Y, minBucket);
        // If we couldn't find a split, then we have a leaf
        if(splitVar == Double.NegativeInfinity){
            new Node(Y)
        }else{
            // Otherwise recursively build the children and create yourself as a vertex
            val left = buildTree(leftX, leftY, minBucket)
            val right = buildTree(rightX, rightY, minBucket)
            new Node(Y, splitVar, splitPoint, left, right)
        }

However, when I go to compile, I get: could not optimize @tailrec annotated method buildTree: it contains a recursive call not in tail position

I've done things like this in OCaml without any problem at all. Is there a work-around for this?

Upvotes: 0

Views: 153

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369556

I think the error message is pretty clear: your method is neither private nor final, therefore it can be overridden, therefore it is not guaranteed that the calls to buildTree will go to the same method. The method needs to be either private or final.

But even if it were private or final, the recursive calls are not in tail position.

Basically, your tail recursive call is neither a tail call nor even guaranteed to be recursive.

Upvotes: 1

Related Questions