Procedural Programming
In most programming languages (C++, Java, python) we generally use what is called “procedural programming” where we work in a very step-wise fashion. Perhaps the archetype of this is the “for-loop”, the work-horse of standard programming. Mathematica, too, has a For
loop. In fact we can use all the standard constructs of procedural programming:
radii={};
For[ i =1, i<10, i++,
radii=radii~Append~RandomReal[]
];
radii
(*Out:*)
{0.914128302537593`,0.3769315906863173`,0.6234932943918361`,0.1322100006893343`,0.1577628966678457`,0.016730303000478397`,0.17548676789547235`,0.8109969085084299`,0.20378370831071368`}
We have a very simple set of steps, here, make a list, radii
, initialize a loop variable i
, then perform a task (appending a Real
to radii
) and incrementing our loop variable i
while some test holds ( i < 10
). Everything is laid out very explicitly and easily to understand. Unfortunately, when writing a large program, having to go through so many steps is a hassle and impedes the development process.
Functional programming, which is almost always defined in contrast to procedural programming, deals with using functions like our usual primitives and passing them through other function accordingly. There are many facets to functional programming, of course, but its most common use is the application of functions to lists.
We can do the above process in a single line using a functional construct:
Table[RandomReal[],10]
(*Out:*)
{0.4137847297182886`,0.9732982192569992`,0.3548496693281973`,0.8582126960787808`,0.15420928011477764`,0.6816139288605962`,0.8404716895591711`,0.9679926345109562`,0.7314841013853948`,0.7997407311341189`}
There are many useful functional constructs we can use that will solve large classes of programming issues for us.