Programming
Mathematica contains a set of program paradigms, which allows writing any program in the best way it can be written in.
Example 1. Procedural programming. Operators are similar to C++, Pascal, ... Appropriation and conditional operator If:
![]()
![]()
Cycle operators are: For, Do, While, Throw, NestWhile. Calculating the sum of the first four natural numbers with intermediate prints:
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
Example 2. Programing the list base. A lot of operations are treated easily as lists. They can be created in different ways, i.e. with the Table operator, by adding to the beginning, end or at a random location etc. Examples of list operations and manipulations are shown below.
![Clear[d] d = {} (* empty list, where this ... n the calculation cell *) For[i = 1, i<6, i ++, d = Append[d, i]] d Prepend[d, a] Append[%, b]](HTMLFiles/index_13.gif)
![]()
![]()
![]()
![]()
Cycle for three dimensional table 'k':
![]()
![]()
| 1 | |||
| 2 | 4 | ||
| 3 | 9 | 27 | |
| 4 | 16 | 64 | 256 |
The next function produces the upper table in a single dimensional list:
![]()
![]()
And this one combines it in pairs:
![]()
![]()
Example 3. Functional programming.
![]()
![]()
If
is a "lear function", its argument places it at the location of #.
![]()
![]()
Example 4. Programming based on rules. The symbol ':=' here means defining the function 'p[]' and 'x_' and 'y_' are formal parameters.
![]()
![]()
![]()
The symbol _ can be changed with a single expression, whereas the symbol __ is a random number of expressions.
![]()
![]()
![]()
![]()
Example 5. Object-oriented programming. Three definitons of functions associated with the object 'h' are shown below.
![h/:h[x_] + h[y_] := hplus[x, y] h/:p[h[x_], x_] := hp[x] h/:f_[h[x_]] := fh[f, x]](HTMLFiles/index_36.gif)
Here is how the three definitons can be isolated.
![]()
![]()
![]()
Example 6. Programming the string base.
![]()
![]()
Example 7. Mixed porgramming paradigms.
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
Exampleр 8. Programs can be written in different styles. This is illustrated below with small programs (functions), each of which calulates n!
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
Created by Mathematica (October 6, 2007)