Is it possible to DRY these 2 methods of a tailrec Node Tree? I have a Tree structure composed by Node class.

I have to @tailrec method that are visiting up to the root.

Those 2 methods are completely similar, but 1 of those is manipulated a "stats" variable to check the visit and return the root, the other just return the root node.

Here the code sample:

class Node(parent: Option[Node], var visited: Int)
@tailrec
def asc(): Node = {
  parent match {
    case None =&gt; this
    case Some(x) =&gt; x.asc()
  }
}

@tailrec
def ascVisited(deltaInc: Inc): Node = {
  visited += deltaInc

  parent match {
    case None =&gt; this
    case Some(x) =&gt; x.ascVisited(deltaInc)
  }
}


Is there any way to reuse the logic of the parent checking and then call recursively the method? I thought with a higher-order function should be possible, but I am not sure is possible with different input argument in the functions.

Any suggestion?

Is it possible somehow to DRY out these 2 bits :

parent match {
  case None =&gt; this
  case Some(x) =&gt; x.asc()
 }
// and
parent match {
  case None =&gt; this
  case Some(x) =&gt; x.ascVisited(deltaInc)
}
I defined a Higher-Order function:

@tailrec
def foldAsc(op: Node =&gt; Node): Node = {
  op(this)       // &lt;= still this statemnt when x=&gt;x is useless.. 
  parent match {
    case None =&gt; this
    case Some(x) =&gt; x.foldAsc(op)
  }
}

def asc(): Node = foldAsc(x =&gt; x)


def ascVisited(deltaInc: Inc): Node = foldAsc { x =&gt;
  visited += deltaInc
  x
}


It is not still optimal but DRYed out a little.