Search code examples
rinterpreter

Advanced: Why ?function(){} works in R


I understand some operators and functions in R need to be backquoted before using the help function. However, I don't understand why ?function(){} also works. Does anyone have any idea on it?


Solution

  • Let's see what happens in ?'s code using the {flow} package, it helps you inspect the logical path your code takes (follow the full lines):

    flow::flow_run(?function(){}, out = "png")
    

    enter image description here

    We see that when the expression is a call we call utils:::.helpForCall

    Let's see what happens there, we cannot call flow::flow_run directly so we call flow::flow_debugonce to set up utils:::.helpForCall and call ? again

    flow::flow_debugonce(utils:::.helpForCall, out = "png")
    ?function(){}
    

    enter image description here

    There we see that when the input is a call we call utils:::.tryHelp on the name of the function as a string. function(){} is a call to function and utils:::.tryHelp("function") opens the help file.


    Bonus

    @rawr wonders why ?cars[1] doesn't work, I haven't looked much into it but at a glance we see where the code takes a different path in .helpForCall:

    flow::flow_debugonce(utils:::.helpForCall, out = "png")
    ?mtcars[1]
    

    enter image description here