Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the sign character accepted in the function definition?

Tags:

function

r

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 {.

like image 827
Peter VARGA Avatar asked Oct 16 '22 04:10

Peter VARGA


1 Answers

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.

  • If -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
like image 58
CinchBlue Avatar answered Nov 15 '22 13:11

CinchBlue