# 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 => this
case Some(x) => x.asc()
}
}

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

parent match {
case None => this
case Some(x) => 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 => this
case Some(x) => x.asc()
}
// and
parent match {
case None => this
case Some(x) => x.ascVisited(deltaInc)
}

• Is this real working code? The braces don't match. What's it for? What's Inc? Please provide some context. See How to Ask. – 200_success May 5 '19 at 18:29
• Edited. Forgot those closing bracing sorry. – Raffaello May 5 '19 at 20:07
• But what do asc() and ascVisited(…) do? You can't ask us to combine them if you don't show us that code too! – 200_success May 5 '19 at 20:09
• That is the code. :/ – Raffaello May 5 '19 at 20:18
• Just make deltaInc optional by giving it a default value of 0. Then you only need one method instead of two. – jwvh May 6 '19 at 6:08

## 1 Answer

I defined a Higher-Order function:

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

def asc(): Node = foldAsc(x => x)

def ascVisited(deltaInc: Inc): Node = foldAsc { x =>
visited += deltaInc
x
}


It is not still optimal but DRYed out a little.

• You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer. – Toby Speight Jun 10 '19 at 8:51
• @TobySpeight the improvement is using a higher order function and DRY the code as was asked. – Raffaello Jun 16 '19 at 19:16