How can i visualize and see the execution in intellij for any scala recursion question?

Viewed 29

I am new to Scala,and I have been trying to learn Scala but I got one of the question in Scala 99 problems, I'm unable to visualize and understand the flow here. Is there any way I can see the how the scala recursion code is behaving and what is happening in every recursive call. Please help me

Below is the code

object p26 {
  def main(args: Array[String]): Unit = {
    val k = 3
    val list = List('a', 'b', 'c', 'd', 'e', 'f')
    println(combinations(k, list))
  }

  def combinations(k: Int, list: List[Any]): List[List[Any]] = {
    list match {
      case Nil => Nil
      case head :: xs =>
        if (k <= 0 || k > list.length) {
          Nil
        } else if (k == 1) {
          list.map(List(_))
        } else {
          combinations(k - 1, xs).map(head :: _) ::: combinations(k, xs)
        }
    }
  }
}
1 Answers

To debug this in IntelliJ just put a breakpoint on the list match line (left click in margin) and then run under the debugger (right click on the play icon next to main). The debugger should stop each time that function is called. You can then see the various values in the debug window, and can step through each line of code to see what is happening.

Please note that this is not a tail recursive function so the tail-recursion tag is not really appropriate.

Related