From macrakis at alum.mit.edu  Fri Apr 17 01:20:19 2009
From: macrakis at alum.mit.edu (Stavros Macrakis)
Date: Thu, 16 Apr 2009 19:20:19 -0400
Subject: [Rd] Using trace
In-Reply-To: <8b356f880904122219q7c966b40h19fd83793de3dd0d@mail.gmail.com>
References: <8b356f880904122219q7c966b40h19fd83793de3dd0d@mail.gmail.com>
Message-ID: <8b356f880904161620qddbc78eq5cc9be3980ed6086@mail.gmail.com>

I posted the query below on r-help, but perhaps r-devel is more
suitable... (I guess "r-devel" should be read as "those who develop
(i.e. write) programs in R" rather than "those who develop R"?)

             -s

I would like to trace functions, displaying their arguments and return
value, but I haven't been able to figure out how to do this with the
'trace' function.

After some thrashing, I got as far as this:

? ?fact <- function(x) if(x<1) 1 else x*fact(x-1)
? ?tracefnc <- function() dput(as.list(parent.frame()), ?#
parent.frame() holds arg list
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?control=NULL)
? ?trace("fact",tracer=tracefnc,print=FALSE)

but I couldn't figure out how to access the return value of the
function in the 'exit' parameter. ?The above also doesn't work for
"..." arguments. ?(More subtly, it forces the evaluation of promises
even if they are otherwise unused -- but that is, I suppose, a weird
and obscure case.)

Surely someone has solved this already?

What I'm looking for is something very simple, along the lines of
old-fashioned Lisp trace:

> defun fact (i) (if (< i 1) 1 (* i (fact (+ i -1)))))
FACT
> (trace fact)
(FACT)
> (fact 3)
?1> (FACT 3)
? ?2> (FACT 2)
? ? ?3> (FACT 1)
? ? ? ?4> (FACT 0)
? ? ? ?<4 (FACT 1)
? ? ?<3 (FACT 1)
? ?<2 (FACT 2)
?<1 (FACT 6)
6

Can someone help? Thanks,

? ? ? ? -s



[Rd] Using trace
Stavros Macrakis