Introduction to Function Programming

Like APL and Mathematica, R programs are functions.  R functions may have any number of arguments and must return a value.  Some functions like plot could produce their output as a side-effect and actually return a null value.  Functions can be dumped out in text readable form using the dump function.  Here is a simple example of the definition of a function to determine if a scalar integer x is a prime number:

is.prime <- function(x) {
!any(x %% 2:ceiling(sqrt(x)) == 0)
}

Remark: I didn't bother to actually check to see if x is a valid sort of argument, so this function might not work if x is not a positive integer.  In practice, if you are just trying to solve a problem for yourself, this approach of not checking and validating the input is ok.  If your code is for other users, you might want to do this and include comments.  To see a modified version incorporating this, click here.

Exercise:  Use is.prime to create another function, say ppairs(n), which determines all the prime pairs up to n.  Solution.