Exercise

Identifying pure functions

A pure function satisfies two properties:

  • Its output only depends on its inputs: when you input a value, the output is always the same.
  • It has no side-effect, that is to say, no effect outside the function.

A lot of functions in R are not pure, yet they are vital for a day to day use of R: when doing an analysis, you need to download files, create a plot, save results…

When programming, you should aim at making your functions either as pure as possible or as impure as possible (for example, a function that downloads a file should only download this file). But for that, you first need to be able to recognize a pure function from an impure one.

This is what we'll do in this exercise: run functions which are either pure or impure, and see what their outputs are.

Instructions 1/4

undefined XP
  • 1

    Run Sys.time(), then Sys.sleep(1), then Sys.time() again, to see how two calls to the same function can lead to different results.

  • 2

    Run nrow(iris), then Sys.sleep(1), then nrow(iris) again, to see how these two calls return the same thing, regardless of time.

  • 3

    Run ls(), which lists the objects in the environment. Create a new object called this, which contains 12, then run ls() again.

  • 4

    Run plot(iris), which creates a basic plot of the iris dataset. See how nothing is printed to the console, and only a side-effect is produced.