5

I tried to create a function and then immediately call it.

function(x){x+1}(3)

This produces some strange result. Fortunately, I already know where I went wrong. I should have let the function statement be evaluated first before attempting to call it.

(function(x){x+1})(3)
# 4

However, I am confused as to what the first line of code actually evaluates to. Is someone able to explain what is going on in the R code below?

a <- function(x){x+1}(3)
a
# function(x){x+1}(3)

class(a)
# [1] "function"

a(3)
# Error in a(3) : attempt to apply non-function

a()
# Error in a() : argument "x" is missing, with no default

(a)
# function(x){x+1}(3)
# <bytecode: 0x128b52c50>

# everything in brackets on the right don't seem to be evaluated
function(x){x+1}(1)(2)(a,b,c)[1:4,d:5,,,][seq_along(letters)]
# function(x){x+1}(1)(2)(a,b,c)[1:4,d:5,,,][seq_along(letters)]
(function(x){x+1}(1)(2)(a,b,c)[1:4,d:5,,,][seq_along(letters)])
# function(x){x+1}(1)(2)(a,b,c)[1:4,d:5,,,][seq_along(letters)]
((function(x){x+1}(1)(2)(a,b,c)[1:4,d:5,,,][seq_along(letters)]))
# function(x){x+1}(1)(2)(a,b,c)[1:4,d:5,,,][seq_along(letters)]
Felix Jassler
  • 1,029
  • 11
  • 22
  • Related: [How do I call the `function` function?](https://stackoverflow.com/questions/54596743/how-do-i-call-the-function-function) – markus Nov 15 '22 at 16:13
  • 2
    If you change your example to `a <- function(x){x}(3)` then something like `a(4)` triggers the error but `a(sqrt)` works fine. Functions can return functions, so R interprets the code as trying to make a function which is then applied to 3. In your case, I suspect that your `a` will always throw an error since I don't think that you can add 1 to a function object and get another function object. – John Coleman Nov 15 '22 at 16:22
  • @JohnColeman Ooh, so `function(x){x}(3)` is basically like `function(x){x(3)}`? – Felix Jassler Nov 15 '22 at 17:35

1 Answers1

5

Actually the curly braces are a call, like a function. The first line is equivalent to

function(x)`{`(x+1)()

As the function is not evaluated, it is not known wether the bracket "call" return a function, thus is valid code. For example:

{mean}(1:2)
# 1.5

`{`(mean)(1:2)
# 1.5

When you run a function definition but do not evaluate it, you actually see the function definition (formals and body) as output.

See ?"{" for more detail.

Ric
  • 5,362
  • 1
  • 10
  • 23
  • Aah that makes sense. So, as someone has mentioned in the comments, `function(x){x}(3)` is essentially the same as `function(x){x(3)}` / `function(x)\`{\`(x)(3)`? – Felix Jassler Nov 15 '22 at 21:47