concept side effect in category R

appears as: side effect, side effects
Machine Learning with R, the tidyverse, and mlr

This is an excerpt from Manning's book Machine Learning with R, the tidyverse, and mlr.

When a function does something other than return a value (such as draw a plot or alter an environment), it’s called a side effect of the function. A function that does not produce any side effects is said to be a pure function.

A simple example of functions that do and do not produce side effects is shown in listing 2.17. The pure() function returns the value of a + 1 but does not alter anything in the global environment. The side_effects() function uses the super-assignment operator <<- to reassign the object a in the global environment. Each time you run the pure() function, it gives the same output; but running the side_effect() function gives a new value each time (and will impact the output of subsequent pure() function calls as well).

Listing 2.17. Creating a list of numeric vectors
a <- 20

pure <- function() {
  a <- a + 1
  a
}

side_effect <- function() {
  a <<- a + 1
  a
}

c(pure(), pure())
[1] 21 21

c(side_effect(), side_effect())
[1] 21 22

Calling functions without side effects is usually desirable because it’s easier to predict what the function will do. If a function has no side effects, it can be substituted with a different implementation without breaking anything in your code.