سؤال

I am learning Funcional Programming in Scala and quite often I need to trace a function evaluation in order to understand better how it works.

For example, having the following function:

def foldRight[A,B](l: List[A], z: B)(f: (A, B) => B): B =
  l match {
    case Nil => z
    case Cons(x, xs) => f(x, foldRight(xs, z)(f))
  }

For the following call:

foldRight(Cons(1, Cons(2, Cons(3, Nil))), 0)(_ + _)

I would like to get printed its evaluation trace, like this:

foldRight(Cons(1, Cons(2, Cons(3, Nil))), 0)(_ + _)
1 + foldRight(Cons(2, Cons(3, Nil)), 0)(_ + _)
1 + (2 + foldRight(Cons(3, Nil), 0)(_ + _))
1 + (2 + (3 + (foldRight(Nil, 0)(_ + _))))
1 + (2 + (3 + (0)))
6

Currently I am doing either manually or injecting ugly print's. How can I achieve that in a convenient elegant way?

هل كانت مفيدة؟

المحلول

I assumed that Cons and :: are the same operations. If you don't mind getting only the current element and the accumulator you can do the following:

def printable(x:Int, y:Int): Int = {
    println("Curr: "+x.toString+" Acc:"+ y.toString)
    x+y
} 
foldRight(List(1, 2, 3, 4), 0)(printable(_,_))  
//> Curr: 4 Acc:0
//| Curr: 3 Acc:4
//| Curr: 2 Acc:7
//| Curr: 1 Acc:9
//| res0: Int = 10

If you want the whole "stacks trace" this will give you the output you asked, although it is far from elegant:

def foldRight[A, B](l: List[A], z: B)(f: (A, B) => B): B = {
  var acc = if (l.isEmpty) "" else l.head.toString
  def newAcc(acc: String, x: A) = acc + " + (" + x
  def rightSide(xs: List[A], z: B, size: Int) = xs.toString + "," + z + ")" * (l.size - size + 1)
  def printDebug(left: String, right: String) = println(left + " + foldRight(" + right)

  def go(la: List[A], z: B)(f: (A, B) => B): B = la match {
    case Nil => z
    case x :: xs => {
      acc = newAcc(acc, x)
      printDebug(acc, rightSide(xs, z, la.size))
      f(x, go(xs, z)(f))
    }
  }
  if (l.isEmpty) z
  else f(l.head, go(l.tail, z)(f))
}

Note: to get rid of the variable 'acc' you can make a second accumulator in the 'go' function


This one also returns the output you asked for, but doesn't obscure foldRight.

class Trace[A](z: A) {
  var list = List[A]()
  def store(x: A) = {
    list = list :+ x
  }

  def getTrace(level: Int): String = {
    val left = list.take(level).map(x => s"$x + (").mkString
    val right = list.drop(level).map(x => s"$x,").mkString
    if (right.isEmpty)
      s"${left.dropRight(4)}" + ")" * (list.size - 1)
    else
      s"${left}foldRight(List(${right.init}), $z)" + ")" * (list.size - level - 1)
  }

  def getFullTrace: String =
    { for (i <- 0 to list.size) yield getTrace(i) }.mkString("\n")

  def foldRight(l: List[A], z: A)(f: (A, A) => A): A = l match {
    case Nil => z
    case x :: xs => store(x); f(x, foldRight(xs, z)(f))
  }
}

val start = 0
val t = new Trace[Int](start)
t.foldRight(List(1, 2, 3, 4), start)(_ + _) 
t.getFullTrace 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top