0
\$\begingroup\$

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)
}
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – 200_success May 5 at 18:29
  • \$\begingroup\$ Edited. Forgot those closing bracing sorry. \$\endgroup\$ – Raffaello May 5 at 20:07
  • \$\begingroup\$ But what do asc() and ascVisited(…) do? You can't ask us to combine them if you don't show us that code too! \$\endgroup\$ – 200_success May 5 at 20:09
  • \$\begingroup\$ That is the code. :/ \$\endgroup\$ – Raffaello May 5 at 20:18
  • 1
    \$\begingroup\$ Just make deltaInc optional by giving it a default value of 0. Then you only need one method instead of two. \$\endgroup\$ – jwvh May 6 at 6:08
-1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Toby Speight Jun 10 at 8:51
  • \$\begingroup\$ @TobySpeight the improvement is using a higher order function and DRY the code as was asked. \$\endgroup\$ – Raffaello Jun 16 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.