Evaluate a function definition upon definition

I am testing some functions that are defined for plumber, and I think it might be a nice hack to be able to pipe a function definition I am creating to a quick evaluation to test it. Is there a way to put a %>% <something> after a function definition to test it? I'm thinking something like this:

function(){"hi"} %>% callit()

I know this will work:

#> (function(){"hi"})()
# [1] "hi"

Where callit will call the function. It would also be nice if callit() could pass arguments if the function has arguments

function(a, b){paste0(a, b, collapse="")} %>% callit(a="x", b="y")

Is there such a structure/form that will work?

callit <- function(.fn,...){

(function(a, b){paste0(a, b, collapse="")}) %>% callit(a="x", b="y")

however this is just :

(function(a, b){paste0(a, b, collapse="")})(a="x", b="y")

with more steps (though it would allow you to inject additional functionality from callit (but you didnt mention needing to do that).
Additionally I would assume that if this is about plumbr functions, they would be named functions, so the focus on anonymous functions seems very odd to me, but good luck to you !

1 Like

Thanks. That is correct, this has to do with plumber. My motivation is to be able to troubleshoot the function at the endpoint in the main file by just appending a few quick lines after the function and evaluating the function in-line to test its behavior rather than running plumber, going to the browser, clicking on the 'try the endpoint' button, and then execute. Thought it would save me a few steps sometimes to not have to leave the source file to test out functionality with this little trick. So it seems possible.

The one thing that seems necessary is that I either name the function definition or have to wrap the function() definition in parenthesis before feeding it downstream via a pipe. I don't think I can do:

function() {"thebody"} %>% ...

But have to do:

(function() {"thebody"}) %>% ...

Yeah, i think thats just how the R parser works. I.e. what should r consider to be on the left of the pipe. Its looking for some complete R statement, and brackets will disambiguate that.

For your case maybe define easy to activate code snippets.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.