Dimitri
Dimitri

Reputation: 8280

Can this function be considered tail recursive?

Here is my function :

    //Data Structures :
    abstract class HuffmanTree
  case class Node(left: HuffmanTree, right: HuffmanTree, chars: List[Char], weight: Int) extends HuffmanTree
  case class Leaf(char: Char, weight: Int) extends HuffmanTree


  def find_char(tree: HuffmanTree, x: Char, accu: List[Int]): (Boolean, List[Int]) = {
    tree match {
      case Leaf(c, _) => ((x == c),accu)
      case Node(left, right, ll, _) =>
      (find_char(left,  x,  accu ::: List(0))._1 || find_char(right, x,  accu :::List(1))._1, accu);
    }
  }

The function takes a huffman tree, a character and accumulator. The purpose of the function is to search the character in the huffman tree and to encode it. So I traverse the tree, when I go to the left, I add 0 to the accumulator and when I go to the right, I add 1 to the accumulator.

I would like to know if this function is tail recursive?

I also have another problem. When I reach a Leaf, the returned accumulator is always empty. Can someone explain me why I have this problem?

Upvotes: 1

Views: 489

Answers (1)

Nicolas
Nicolas

Reputation: 24759

General hint: the @tailrec annotation can be used to check if a method is tail recursive.

Basically in you case, it is not tail recursive: in the Nodecase, there is an || operator between the two recursive calls.

Considering the empty list of Int. It's straightforward: you return the original value of accu in any case. If you called find_char with an empty list as a second parameter, you can't obtain something else than the empty list.

Upvotes: 11

Related Questions