Skip to content

Instantly share code, notes, and snippets.

@zeehio
Created February 17, 2022 10:41
Show Gist options
  • Save zeehio/e7d78790f57015c846a2f72441cf9436 to your computer and use it in GitHub Desktop.
Save zeehio/e7d78790f57015c846a2f72441cf9436 to your computer and use it in GitHub Desktop.
Referencial transparency in R

Referencial transparency is a property of most programming languages, where the name of the variables does not affect the outcome.

Let's start with a simple example:

add1 <- function(variable) {
  return(variable + 1)
}

add1(1)
#> [1] 2
x <- 1
add1(x)
#> [1] 2
y <- 1
add1(y)
#> [1] 2
add1(variable = y)
#> [1] 2

The name of the variable does not affect the outcome, name it x, y, or whatever you like. This happens in most programming languages.

However, in R we can find out the name of the variable, and behave like trolls:

add1 <- function(variable) {
  original_varname <- as.character(substitute(variable))
  if (original_varname == "z") {
    return(variable + 200) # TROLOLOLOLO
  }
  return(variable + 1)
}

x <- 1
add1(x)
#> [1] 2
y <- 1
add1(y)
#> [1] 2
z <- 1
add1(z)
#> [1] 201

😨 Why would anyone do this? Sometimes it's convenient! 👍

hundreds <- c(100, 200, 300)
thousands <- c(1000, 2000, 3000)
data.frame(hundreds, thousands)
#>   hundreds thousands
#> 1      100      1000
#> 2      200      2000
#> 3      300      3000

Look at those convenient column names! 😃

Or in plots:

hundreds <- c(100, 200, 300)
thousands <- c(1000, 2000, 3000)
plot(hundreds, thousands)

Look at those axes labels!

Referencial transparency is very convenient for interactive programming and coding, but it can become a nightmare when programming, so use it sparingly!

Created on 2022-02-17 by the reprex package (v2.0.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment