I'm working on a problem where I am trying to do selective tracing of some function calls. The specific problem I am trying to do is to trace a Fibonacci call but not show any calls that result in 1. For example,
fib(4) would return
fib 2 => 2
fib 2 => 2
fib 3 => 3
fib 4 => 5
instead of
fib 0 => 1
fib 1 => 1
fib 2 => 2
fib 1 => 1
fib 0 => 1
fib 1 => 1
fib 2 => 2
fib 3 => 3
fib 4 => 5
To do this, we should implement the function trace_test. We are given the following code
def wrapper [A,V,B](pre:A=>V,post:(V,B)=>Unit,post_exc: (V,Exception)=>Unit)
(f:A=>B) (x:A) : B = {
val v = pre(x)
try{
val r = f(x)
post (v,r)
return r
}
catch{
case e: Exception =>{ post_exc(v,e)
throw e
}
}
}
def tracer [A,B](fn_str:String) (pr_arg:A=>String)
(pr_res:B=>String) (f:A=>B) (x:A) =
{
def pre(x:A) = (fn_str + " " + (pr_arg (x)))
def post(v:String,r:B) = println (v+" => "+(pr_res(r)))
def postEx(v:String,e:Exception) = println (v+" => Exception")
wrapper (pre,post,postEx) (f) (x)
}
and asked to modify the tracer method to complete the problem so that when the following is called, it will trace the method without any ones as output:
def fib3 (n:Int):Int ={
def pr_test(x:Int) = x>1
def aux (n:Int) = if (n<=1) 1 else fib3 (n-1)+(fib3(n-2))
trace_test("fib") (pr_test) (intToString) (intToString) (aux) (n)
}
The way I thought I would do this is by adding a conditional statement. So, I modified it to look like this:
def trace_test [A,B](fn_str:String) (pr_test:A=>Boolean)
(pr_arg:A=>String) (pr_res:B=>String) (f:A=>B) (x:A) ={
if (pr_arg(x).toInt == pr_test){
def pre(x:A) = (fn_str + " " + (pr_arg (x)))
def post(v:String,r:B) = println (v+" => "+(pr_res(r)))
def postEx(v:String,e:Exception) = println (v+" => Exception")
wrapper (pre,post,postEx) (f) (x)
}
}
However, now I am seeing an error on the line where I call trace_test because it is telling me "Type mismatch: found : Any required Int.
What does this error mean? What requires an Int here and what is returning an Any?
Aucun commentaire:
Enregistrer un commentaire