I was asked to compare two trees. Something like below:
case class Node(elem:String, child:List[Node])
To compare each element of the tree, I have the following functions:
def compare(n1:Node, n2:Node): Boolean { if(n1.elem == n2.elem){ return compare(n1.child, n2.child) } } def compare(c1:List[Node], c2:List[Node]): Boolean { while (c1.notEmpty) { //filter, map etc call function above to compare the element recursively } }
Basically the algorithm for each element in n1, we check the correspondence in n2. I was told that this is a very important and non-functional way. What would be a functional way to achieve this behavior. In other words, how do we remove the while loop when comparing the list of children?
source share