function
is a primitive function :
`function`
.Primitive("function")
Its second argument is the body, it's a quoting function, meaning this second argument is not evaluated. These are equivalent :
fun1 <- function(x) x + 5
fun2 <- `function`(NULL, x + 5)
formals(fun2) <- alist(x=)
fun3 <- do.call( 'function', list(as.pairlist(alist(x=)), quote(x+5)))
identical(fun1,fun2)
[1] TRUE
identical(fun1,fun3)
[1] TRUE
See this question adressing why we can't use the function function
as we can with other : How do I call the `function` function?
The syntax used for fun1
is function(...) body
, where ...
will be mapped to a pairlist.
{
is itself a function. Unlike (
, {
is never treated specially by the parser.
So when you have a single call in your expression, the {
is not needed, not because function
's syntax is designed to be flexible, but because it's not part of the function
syntax.
I tend to agree that it's good practice to use curly braces for consistency, when you want to use trace
for example inconsistencies are annoying. It's generally of little consequences though, and it's not enforced by base R :
mean
# function (x, ...)
# UseMethod("mean")
# <bytecode: 0x000000000e146288>
# <environment: namespace:base>
body(mean)
# UseMethod("mean")
As a side note rlang
has a nice function to be able to get a consistent body output:
rlang::fn_body(mean)
# {
# UseMethod("mean")
# }