Search code examples
rfunctionmagrittr

Function declaration in R and its evaluation?


Sorry for not being more specific in my question title but I was not sure how to phrase it.

I am just trying to understand how function declarations work in R.

library(magrittr)
library(compiler)

fn1 <- function(x) {x + 1} %>% cmpfun()
fn2 <- (function(x) {x + 1}) %>% cmpfun()

fn1(1) # gives an error
fn2(1) # works as expected

Why do I need parentheses around the function declaration so that fn2 works and fn1 does not?

If function is just like any other function, then why are not function calls (as in function declarations) obeying the normal syntax... From the help page on function, its syntax is:

function( arglist ) expr
return(value)

Solution

  • Because

    fn1 <- function(x) {x + 1} %>% cmpfun()
    

    is the same as

    fn1 <- function(x) {
        {x + 1} %>% cmpfun()
    }
    

    So like the documentation says: function( arglist ) expr -- basically everything after the function(x) is being treated as a single expression. When there are parenthesis, it knows when to "stop" the expression.

    Which is different from

    fn2 <- (function(x) {x + 1}) %>% cmpfun()
    

    which is more like

    fn2 <- `%>%`( function(x) {x + 1}, cmpfun())
    

    So the first is just defining a function while the second is actually calling the pipe operator.