Due to a typo I found out this code works [note the repeated -
in the 2nd line]
foo <- function()
-------------------------
{
1
}
Calling foo()
returns -1
. The number of -
determines if the returned value is positive or negative [odd number returns a negative number].
I didn't find anything regarding this R function definition so I am now asking why is this allowed and what is the purpose of this.
Even the official R documentation doesn't mention this at all. Any idea?
A note: invisible(1)
doesn't work. The output is not suppressed when there is a sign character before the opening {
.
You've tripped on the strange allowances of R's syntax rules for function bodies.
Since the syntax of functions in R allow for any expression after the argument list, usually R functions provide a list of expressions surrounded by {}
. This is sometimes known in other languages as an expression "block." In R, the "evaluation value" of a block is the evaluation value of the last expression in the block.
-1
is a valid expression, then -{1}
is a valid expression as well.-
is also the unary negation operator, and it is repeatable in R. Therefore:
1 = 1
-1 != -1
--1 == 1
----1 == 1
-----1 == -1
So the evaluation goes:
foo <- function() ------------------------- {1}
foo <- function() ------------------------- 1
foo <- function() -1
And due to R's syntax rules, you could as easily go:
foo <- function() -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With