Search code examples
rtreenested-loopsnested-listsr6

Recursive search for a node in nested R6 tree - How to break the loop?


I am trying to implement a search algorithm in R similar to the following, that searches for a node in a tree of nested R6 classes:

search = function(node){
  if (private$name == node){
    self
  } else {
    if(all(!is.na(private$list))){
      for (i in 1:length(private$list)){
        private$list[[i]]$search(node)
      }
    } 
  }
}

Here, search is a public function of the R6 class "Node". This class has a private name and a private list of other nodes - so it is a parent node of a nested tree R6 classes.

The issue is that the algorithm visits the correct node, but the function fails to generate an output because the nested loop does not break, and it continues to cycle through all of the nodes until it visits all of them. Using return(self) does not seem to make a difference.

Is there a way of breaking the outer loop by accessing the attributes of the parent, etc?

I highly appreciate any help!


Solution

  • It is not quite clear to me what you wish to achieve, but perhaps this solves it:

    
          for (i in 1:length(private$list)){
            n <- private$list[[i]]$search(node)
            if(!is.null(n)) {
              return(n)
            }
          }