Felix Jassler
Felix Jassler

Reputation: 1531

Directly calling an anonymous function

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)]

Upvotes: 5

Views: 182

Answers (1)

Ric
Ric

Reputation: 5722

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.

Upvotes: 5

Related Questions