(Sections 14.1 - 14.2)
Programming Paradigm
A programming paradigm is a way to describe some of the features of programming languages.Often a paradigm includes principles concerning the use of these features, or embodies a view that these features have special importance and utility in good programming practice.
Procedural Programming
A programming paradigm that solves problems with programs that can be broken up into collections of variables, data structures and procedures.This paradigm tends to draw a sharp distinction between variables and data structures on the one hand and procedures on the other.
So far we have worked mostly with a procedural paradigm.
Procedural Programming
A programming paradigm that stresses the central role of functions.R is not a “pure” functional programming language, but it provides a lot of support for the functional programming paradigm.
Let’s examine the basic ideas of functional programming, as they appear in R.
There are actually three function calls involved in the above code!
The assignment operator <-
is actually a function in disguise:
Example:
Really?
<-
returns the assigned value (invisibly).
The sub-setting operator [
is actually a function in disguise:
The double-colon operator is also a function in disguise:
can be re-written as:
Ugh! But is shows that in R almost everything that happens is the result of a function call.
In programming parlance, a first-class citizen is “entity which supports all the operations generally available to other entities” (see Wikipedia).
Functions in R can:
Recall that any external result produced by a function (other than what the function returns) is called a side-effect of the function.
In the following call, a name-value pair (a and 5) is added to the Global Environment:
In the following call there is output to the Console:
In R we can’t avoid side-effects entirely if we want our programs to do something practical.
But we try to minimize them by having the function return needed information, as much as possible.
We will try to accomplish tasks with a small sequence of carefully-defined functions, so that calls to these functions explain by themselves what is going on.
In particular, calls to higher-order functions will replace loops, to a large extent.