explorations/modifyCode/Notes.md

Rewriting Code with codetools::walkCode()

The idea is to reassemble the language objects and collect information.

Examples of what we want to do are

These operations will allow us to implement

Moving Functions out of a Function

The following is a very simple example, intentionally so.

foo =
function(x, lambda = 2)
{
   alpha = lambda/nrow(x)

   do = function(val)
             val * alpha

   apply(x, 2, do)
}

We want to extract do as a separate function.

It needs alpha, so we would add that as an additional parameter. We write it as

do = function(val, alpha)
         val * alpha

Now, we need to add alpha in the calls to do. We'd rewrite foo as

foo =
function(x, lambda = 2)
{
   alpha = lambda/nrow(x)
   apply(x, 2, do, alpha)
}

A simpler version is when the original function calls the nested function directly.

foo =
function(x, lambda = 2)
{
   alpha = lambda/nrow(x)

   do = function(val)
             val * alpha

   a = do(x[, 1])
   b = sum(do(x[ !is.na(x[ ,2]), 2]))   
}

We would rewrite this as

foo =
function(x, lambda = 2)
{
   alpha = lambda/nrow(x)

   a = do(x[, 1], alpha)
   b = sum(do(x[ !is.na(x[ ,2]), 2], alpha))   
}

Todo

addParams



duncantl/CodeAnalysis documentation built on June 12, 2025, 6:44 a.m.