You are on page 1of 75

Cambridge Books Online

Programming with Mathematica®
An Introduction
Paul Wellin
Book DOI:
Online ISBN: 9780511972942
Hardback ISBN: 9781107009462

5 - Functional programming pp. 115-188
Chapter DOI:
Cambridge University Press

Functional programming
Higher-order functions · Map · Apply · Thread and MapThread · The Listable attribute · Inner
and Outer · Select and Pick · Iterating functions · Nest · FixedPoint · NestWhile · Fold · Defining
functions · Compound functions · Scoping constructs · Pure functions · Options · Creating and
issuing messages · Hamming distance · Josephus problem · Regular polygons · Protein
interaction networks · Palettes for project files · Operating on arrays

Functional programming, the use and evaluation of functions as a programming paradigm, has a
long and rich history in programming languages. Lisp came about in the search for a convenient
language for representing mathematical concepts in programs. It borrowed from the lambda
calculus of the logician Alonzo Church. More recent languages have in turn embraced many
aspects of Lisp – in addition to Lisp’s offspring such as Scheme and Haskell, you will find elements of functional constructs in Java, Python, Ruby, and Perl. Mathematica itself has clear
bloodlines to Lisp, including the ability to operate on data structures such as lists as single objects
and in its representation of mathematical properties through rules. Being able to express ideas in
science, mathematics, and engineering in a language that naturally mirrors those fields is made
much easier by the integration of these tools.
Functions not only offer a familiar paradigm to those representing ideas in science, mathematics, and engineering, they provide a consistent and efficient mechanism for computation and
programming. In Mathematica, unlike many other languages, functions are considered “first class”
objects, meaning they can be used as arguments to other functions, they can be returned as
values, and they can be part of many other kinds of data objects such as arrays. In addition, you
can create and use functions at runtime, that is, when you evaluate an expression. This functional
style of programming distinguishes Mathematica from traditional procedural languages like C and
Fortran. A solid facility with functional programming is essential for taking full advantage of
the Mathematica language to solve your computational tasks.

Downloaded from Cambridge Books Online by IP on Wed May 18 01:16:10 BST 2016.
Cambridge Books Online © Cambridge University Press, 2016

Functional programming


5.1 Introduction
Functions are objects that operate on expressions and output unique expressions for each input.
For example, here is a definition for a function that takes a vector of two variables as argument
and returns a vector of three elements.

f@8u_, q_<D := :Cos@q D

1 - u2 , Sin@q D

1 - u2 , u>

You can evaluate the function for numeric or symbolic values.


f@80, 0.5<D
80.877583, 0.479426, 0<
f@8-1 ê 2, y<D


3 Cos@yD,


3 Sin@yD, -




Functions can be significantly more complicated objects. Below is a function that operates on
functions. It takes two arguments: a function or expression, and a list containing the variable of
integration and the integration limits.

Integrate@Exp@I p xD, 8x, a, b<D
 I‰Â a p - ‰Â b p M



This particular function can be also be given a different argument structure: a function and a

Integrate@Exp@I p xD, xD
 ‰Â p x



Whereas procedural programs provide step-by-step sets of instructions, functional programming involves the application of functions to their arguments and typically operates on the entire
expression at once. For example, here is a traditional procedural approach to switching the
elements in a list of pairs.

lis = 88a, 1<, 8b, 2<, 8g, 3<<;


temp = Table@0, 8Length@lisD<D;

Downloaded from Cambridge Books Online by IP on Wed May 18 01:16:10 BST 2016.
Cambridge Books Online © Cambridge University Press, 2016

-6. Having a large vocabulary of built-in functions will not only make it easier to follow the programs and do the exercises here.doi. then extracting and putting parts of the list into temp one-by-one. we first take a look at some of the most powerful and useful functional programming constructs in Mathematica – the so-called higher-order functions such as Map. The functional approach.253. In[12]:= Select@data. b<. b<. a<. 83.50788  10-6 .29973  10-6 .73666  10-6 . lis@@i. 8i. Apply and Thread – and then discuss the creation of functions. -0.09181  10-6 .50. using many of the list manipulation constructs discussed earlier. 3. 2016 . lisD 881.00001 < x < 0. 1DD<. In[10]:= Out[10]= Map@Reverse. -8. One of the unique features of a functional language such as Mathematica (and also Lisp. 7. Scheme. 106 E. but will enhance your own programming skills as well.5. 2DD. The procedural approach required first allocating an array. g<< Here is a functional approach to solving the same problem.53306  10-6 . g<< This simple example illustrates several of the key features of functional programming. 1. of the same size as lis.1 Introduction In[8]:= Out[9]= 117 Do@temp@@iDD = 8lis@@i. meaning that you do not need to formally declare such a function. 2.50 on Wed May 18 01:16:10 BST 2016. -1. Downloaded from Cambridge Books Online by IP 157. 83. although implying an iteration. avoids an explicit looping structure. The Map function takes the Reverse function as an argument and uses it to operate on the list directly. For example.006 Cambridge Books Online © Cambridge University Press. In Mathematica this is implemented through pure functions. 82. In[11]:= data = RandomRealA8-1. In this chapter.05057  10-6 . looping over lis. 82. 6.6.00001DD Out[12]= 96.90283  10-6 . A functional approach often allows for a more direct implementation of the solution to a problem.1017/CBO9780511972942. temp. a<. 1<. temp 881. we use a pure function below to filter data for values in a narrow band around zero. Length@lisD<D. It is well worthwhile to spend time familiarizing yourself with these functions from the chapter on lists. Function@x. Haskell. without creating a formal function definition. http://dx.69555  10-6 = We will introduce and explore pure functions in Section 5. and others) is the ability to create a function at runtime.94237  10-6 . especially when list manipulations are involved. and finally returning the value of temp.

geometry. Map Map applies a function to each element in a list. finally.7.2 Functions for manipulating expressions Three of the most powerful functions. which are used to extract elements of an expression based on some criteria of interest.5. touching on areas as diverse as signal processing. 5. cD essentially wraps the function f around each of the elements of g. f@bD. b. which will prove useful in manipulating the structure of your expressions. we put a lot of the pieces together from this chapter and the chapters on lists and on patterns to program more extensive examples and applications. mapping a function f over the expression g@a. Finally. in this section we introduce Select and Pick . These are discussed in Section 5. bioinformatics. and Thread. Providing options and issuing messages when things goes wrong are common mechanisms for doing this and they are introduced in Section 5.50. Apply . 2016 .006 Cambridge Books Online © Cambridge University Press. we introduce them in this chapter to start building up the complexity of our examples. :3. They provide efficient and sophisticated ways of manipulating expressions in Mathematica. Developing your functions so that they behave like built-in functions makes them easier to use for you and users of your programs.Functional programming 118 Localization of variables.50 on Wed May 18 01:16:10 BST 2016.253. In[2]:= Out[2]= Map@f. 8a. http://dx. In[1]:= Out[1]= MapBHead.doi.1017/CBO9780511972942. f@cDD Downloaded from Cambridge Books Online by IP 157. f@cD< More generally. or being interfered by. allows you to isolate symbols and definitions that are local to a function in order to keep them from interfering with. b. Although optional arguments and messaging are not specific to functional constructs. and some of those most commonly used by experienced Mathematica programmers are Map. p>F 7 8Integer. We will also briefly look at some related functions (Inner and Outer ). f@bD. common to many modern programming languages. and data processing. In[3]:= Out[3]= Map@f. 22 . c<D 8f@aD. b. Symbol< This can be illustrated using an undefined function f and a simple linear list. In this section we will discuss their syntax and look at some simple examples of their g@a. These higher-order functions are in the toolkit of every experienced Mathematica programmer and they will be used throughout the rest of this book. cDD g@f@aD. Rational. global symbols.

1 + g2 = While it does make your code a bit more compact. 882. Experienced Mathematica programmers and those who prefer such an infix notation tend to use them liberally. exprE. a<. b. We will use the longer form in general in this book but encourage you to become comfortable with either syntax as it will make it easier for you to read programs created by others more readily.006 Cambridge Books Online © Cambridge University Press. vecD 95. c<D. 87. Hence the above computation can also be written as: In[9]:= Out[9]= f êü vec 95. b. g<.50 on Wed May 18 01:16:10 BST 2016. you will need to define your own function to perform a computation on each element of a list.253. c<D is represented internally as 3. 6<. b<.50. In[8]:= Out[8]= Map@f. Here is a list of three elements. http://dx. 3<<D 882. use Reverse with Map. p. 88a. In[4]:= Out[4]= Map@Reverse. 8f. cD). In[5]:= Out[5]= Map@Sort. 81. you could first define a function that performs this computation on its arguments. except in that example g is replaced with List (remember that FullForm@8a. 2016 . 1 + g2 = The Map function is such a commonly used construct in Mathematica that a shorthand notation exists for it: fun êü expr is equivalent to MapA fun. 8e. 5. 1 + p2 .doi. In[6]:= vec = 82. will then wrap f around each element and evaluate f of those elements. 3. Map is expressly designed for this sort of computation. b. 1.1017/CBO9780511972942. In[7]:= f@x_D := x2 + 1 Mapping this function over vec. d<. 4. 8a. 8d. c<. 6. If you wished to square each element and add 1. 4. The real power of the Map function is that you can map any function across any expression for which that function makes sense.2 Functions for manipulating expressions 119 This symbolic computation is identical to Map@f. to reverse the order of elements in each list of a nested list. 1 + p2 .5. 3. e<< The elements in each of the inner lists in a nested list can be sorted. 8c. 7<< Often. For example. Downloaded from Cambridge Books Online by IP 157. f<<D 88b. 5<. the use of such shorthand notation comes at the cost of readability.

3. except we are using the internal representation of the list 8a. the head List has been replaced by Plus . exprD as replacing the head of expr with h. the above computation could be written as follows: In[15]:= Out[15]= Plus üü 81. by default. Map operates at level 1.50. g@a. c. b. Apply is used to change the structure of an expression. http://dx. cD The elements of List are now the arguments of h. exprE. b. 4D has been changed to Plus@1. 3. cD The following computation shows the same thing. List@a. c<D h@a. cD with h. 4D or. If the second argument is a list. cDD h@a. 2. b.006 Cambridge Books Online © Cambridge University Press.1017/CBO9780511972942. By In[11]:= Out[11]= Apply@h. 4<D 10 Plus@a. In[12]:= Out[12]= Apply@h. b. b. for example. 8a. cD and Apply replaced the head of g@a. Essentially. That is. you should think of Apply@h. 81. cDD h@a. in other words. In[14]:= Out[14]= Plus@a. b. 3.doi.Functional programming 120 Apply Whereas Map is used to perform the same operation on each element of an expression. 3. 2. Downloaded from Cambridge Books Online by IP 157. 2. in MapAh. 4< 10 One important distinction between Map and Apply concerns the level of the expression at which each operates. 2016 . cD The function h was applied to the expression g@a. dD a+b+c+d Like Map. b. b.50 on Wed May 18 01:16:10 BST 2016. exprE. List@1. c< here to better see how the structure is changed. Apply has a shorthand notation: the expression fun üü expr is equivalent to ApplyA fun. dD is the internal representation of the sum of these four symbols that you would normally write a + b + c + d.253. c. So. but not deeper. b. if expr consists of a nested list. 2. b. In[10]:= Out[10]= Apply@h. h will be applied to each of the sublists. So. b. In[13]:= Out[13]= Apply@Plus. applying h to that expression simply replaces its head (List ) with h. In the following example. h will be applied to each element at the top level of expr.

2. b<. In[20]:= Out[20]= Apply@Plus. 7<<. 7D< Applying at the default level 0. 7<< 8p@1. 7D< Downloaded from Cambridge Books Online by IP 157. then you have to specify that explicitly using a third argument to Map.5. That is. its Head ) and replaces it with h. 6.006 Cambridge Books Online © Cambridge University Press. h@bD<. 881. 2. 8c. d<<D 8h@8a. In[23]:= Out[23]= p üüü 881.50 on Wed May 18 01:16:10 BST 2016. expr. 81<D 8p@1. p@5. bD. In[17]:= Map@h. This is just vector addition. 8c. 7<<D 86. 88a. 881. think of Plus . In[22]:= Out[22]= Apply@Plus. 2016 . 3D. p@5. 88a. 6. h@dD<< Apply . d<D< If you wish to apply h at a deeper level. 3D. if you wish to apply h at a different level. 881. is quite different. exprE. operates at level 0 by default. b<. to apply Plus to each of the inner lists. b<D. on the other hand. 2. 81<D 8h@a. 88a. In[19]:= Out[19]= Apply@h. you need to specify that Apply will operate at level 1.doi. b<. 88a. 6. 3<. 18< If you are a little unsure of what has just happened. In[18]:= Out[18]= Apply@f. 3<. d<<. h@c. instead of p. in ApplyAh. d<<D f@8a. 6. 10< Applying functions at level 1 is also a common task and it too has a shorthand notation: fun üüü expr is equivalent to ApplyA fun. 6. b<.50. Apply looks at part 0 of expr (that is. 7<<. 81<E. dD< For example. d<D Again. 6. d<<. 3<. 8h@cD. consider the following example and. 85. adding element-wise. 85. 2. b<. In[21]:= Out[21]= Apply@p. 8. 2.2 Functions for manipulating expressions In[16]:= Out[16]= 121 Map@h. 8c. 85.253. 3<. h@8c. 85. 8c. 2. 82<D Out[17]= 88h@aD. then you have to specify that explicitly using a third argument to Apply .1017/CBO9780511972942. 81<D 86. http://dx.

%. g@b. z<< Apply@g.Functional programming 122 Thread and MapThread The Thread function “threads” a function over several lists. x<.doi. 8. g@b. 8x. It differs from Thread in that it takes two arguments – the function that you are mapping and a list of two (or more) lists as arguments of the function.66< Downloaded from Cambridge Books Online by IP 157. x3 Ø 5. this threads the Equal function over the two lists given as its arguments. xD. y.2. We start off with a list of variables and a list of values. For and so on. we create a list of rules. 8x. x4 . yD. 5.66<. xD. yD. b ã y. b. y. 8c. In[26]:= Out[26]= In[27]:= Out[27]= Transpose@88a.21. b.253. z<DD 8g@a.7. It creates a new list in which the corresponding elements of the old lists are paired (or zipped together). 8x.006 Cambridge Books Online © Cambridge University Press. x4 Ø 8. 2.7. Equal@c. c<. 6. Equal@b. x3 . %D 8Equal@a. In[25]:= Out[25]= MapThread@g. z<<D 88a. 8b. c<.5. y<. c<. From these two lists. then extracting the next element in each list and wrapping the function around them. g@c. 81<D 8g@a.1017/CBO9780511972942. http://dx. yD. x2 .50 on Wed May 18 01:16:10 BST 2016. zD< With Thread. wrapping a function around them. In[24]:= Out[24]= Thread@g@8a. x2 Ø 2. 2016 . y.21. x5 Ø 6. g@b. c ã z< Map@FullForm. yD. valuesDD 8x1 Ø 1. you can fundamentally change the structure of the expressions you are using. g@c. You can think of it as extracting the first element from each of the lists.2.5. g@c. zD< You can accomplish the same thing with MapThread. z<<D 8g@a. xD. y. In[28]:= Out[28]= In[29]:= Out[29]= Thread@Equal@8a. b. b.50. x5 <. In[30]:= vars = 8x1 . 88a. zD< You could perform this computation manually by first zipping together the two lists using Transpose. and then applying g at level one. In[32]:= Out[32]= Thread@Rule@vars. In[31]:= values = 81. 8x. z<DD 8a ã x. zD< Here is another example of the use of Thread. xD. c<.

2016 . these functions are automatically threaded onto the elements of the lists. many of the built-in functions that take two or more arguments have the property that. 86. 2<<D. In[37]:= Out[37]= Map@Log. In[33]:= Out[33]= MapThread@Power. 2<.50 on Wed May 18 01:16:10 BST 2016. 1<. 882. 932 . 2<<D 832. 1.2 Functions for manipulating expressions 123 Notice how we started with a rule of lists and Thread produced a list of rules. when multiple lists are the arguments. 1. 3. For example. this is essentially vector addition. http://dx. 9< Using Trace . 82. 925 . 6. In[36]:= Log@8a. 6. 6. 0< You get the same result using Map.5. 1.1017/CBO9780511972942. 2<<D êê Trace 9MapThread@Power. In[34]:= Out[34]= MapThread@Power. In other words. the corresponding elements in the three lists are placed in a list structure (note that Transpose would do the same thing). 1.253. 961 . 882. 1. 885. the function is automatically applied to all the elements in the list. the Log function has this attribute. the direct approach is much more efficient for large computations. 6. 6. Downloaded from Cambridge Books Online by IP 157. 4. 6. but it is a bit more to write and. 32 =. 4<. 85. 1. when a list is the argument. 84. 32=. 1<D 8Log@aD. the base and the exponent.doi. you can view some of the intermediate steps that Mathematica performs in doing this calculation. 4. For example. In this way. 3<. In[35]:= Out[35]= MapThread@List. as we will see in Chapter 12.50. 61 . 882. 4<<D 885. 3<. you might think of Thread as a generalization of Transpose. 85. E.006 Cambridge Books Online © Cambridge University Press. E. 3<. 8a. the function is automatically applied to all the corresponding elements in the list. 9<= Using the List function. 832. 0< Similarly. Here are a few more examples of MapThread. 4<< The Listable attribute Many of the built-in functions that take a single argument have the property that. 85. these functions are automatically mapped on to the elements of the list. 9. Power takes two arguments. 83. 925 . so the following raises each element in the first list to the power given by the corresponding element in the second list. 1<D Out[36]= 8Log@aD. 9<. 9=. In other words.

c. b. Protected< Attributes@PlusD 8Flat. Protected< By default. Many of Mathematica’s built-in functions have this attribute. In[39]:= Out[39]= MapThread@Plus. d<D If you want a function to have the ability to thread over lists. It does not clear any attributes associated with the symbol. 2<<D 89. http://dx. Orderless. In[43]:= SetAttributes@g. NumericFunction. b. d<D Out[44]= 8g@aD. 5< This gives the same result as using the Plus function with MapThread. user-defined functions do not have any attributes associated with them. g@cD.doi. 85. g@bD. d<D Out[42]= g@8a. OneIdentity. In[45]:= Clear@gD In[46]:= ?g Global`g Attributes@gD = 8Listable< You can use ClearAttributes to clear specific attributes associated with a symbol. 6. ListableD In[44]:= g@8a.4 that clearing a symbol only clears values associated with that symbol. So. 6. Listable. 3<. NumericFunction. 5< Functions that are either automatically mapped or threaded onto the elements of list arguments are said to be Listable .1017/CBO9780511972942. 1. c. 884. if you define a function g. for example. 7.50 on Wed May 18 01:16:10 BST 2016. g@dD< Recall from Section 2. 2< 89. 7. In[47]:= ClearAttributes@g. c. 2016 .org/10. it will not automatically thread over a list. b. give it the Listable attribute using SetAttributes. ListableD Downloaded from Cambridge Books Online by IP 157.Functional programming 124 In[38]:= Out[38]= 84. 3< + 85.50. In[40]:= Out[40]= In[41]:= Out[41]= Attributes@LogD 8Listable.253. In[42]:= g@8a. 1.006 Cambridge Books Online © Cambridge University Press.

3<. 8a. This is a generalization of the mathematical outer product. u2 .1017/CBO9780511972942. c<. obtained by wrapping Times around each pair of elements. 8y. 4<<.006 Cambridge Books Online © Cambridge University Press. 4<D 88f@x. f@b. v2 . 2<. 3D. 8x. f@y. In[53]:= Out[53]= In[54]:= Out[54]= Inner@List. 8u1 . you can create lists of ordered pairs that combine the elements of several lists.50 on Wed May 18 01:16:10 BST 2016. you can see that Inner is really a generalization of the mathematical dot product. In[49]:= Out[49]= Outer@f. In[51]:= Outer@Times. gD g@f@a. 8f@y.5. d + e + f< Inner@Times. Downloaded from Cambridge Books Online by IP 157. 2D. 8y. y2 . 8x1 . e. 8x. f@y. which produces a matrix from a pair of vectors. PlusD 8a + b + c.2 Functions for manipulating expressions In[48]:= 125 ?g Global`g Inner and Outer The Outer function applies a function to all the combinations of the elements in several lists. v3 . In[50]:= Out[50]= Outer@List. 82. In[52]:= Out[52]= Inner@f.doi. v4 <D êê MatrixForm Out[51]//MatrixForm= u1 v1 u1 v2 u1 v3 u1 v4 u2 v1 u2 v2 u2 v3 u2 v4 u3 v1 u3 v2 u3 v3 u3 v4 With Inner . http://dx. b. y<. y1 . 8d. z2 <. f<. PlusD x1 x2 + y1 y2 + z1 z2 Looking at these two examples. you can thread a function onto several lists and then use the result as the argument to another function.253. 8x. 82. 8d. 8x2 . f@x. 2016 . fDD This function lets you carry out some interesting operations. 4D<. e. f@c. 4<<< Here is the classical outer product of two vectors. 3. f@x. b. 8x. 2D. 4<D 888x. c<. z1 <. dD. f<. eD. 2<. 3D. 3<. 88y. y<. 8a. u3 <. 8v1 .50. 4D<< Using the List function as an argument.

7. 8191. 2 147 483 647.8705.doi. In[58]:= In[59]:= data = 824. In[61]:= Out[61]= Pick@8a. In[57]:= Out[57]= Select@Table@2n .006 Cambridge Books Online © Cambridge University Press. 131 071.Functional programming 126 In[55]:= Out[55]= Dot@8x1 .1331. 4. 524 287.1. 23. y2 .1619. 1. 9. a common task is to extract all those elements that meet some criteria of interest.1039. y1 . 24. predicateE returns all those elements in expr that pass the predicate test. 21.7762<.321. 8.4736. True<D 8a.8705. 7. PickAexpr. For example. 6.1619. 39. say between 20 and 30.39. z1 <.669. inRangeD 824. 24. inRange. 6. For example. 3. 25. False. 31. 127. For example. 2 305 843 009 213 693 951.8856.669. e< Downloaded from Cambridge Books Online by IP 157. e<. 2. 20. 24.8177.50. c.8856. 14. we first create a function.8177. 21.50 on Wed May 18 01:16:10 BST 2016. 25. 22. 618 970 019 642 690 137 449 562 111< You can also create your own predicates to specify the criteria in which you are interested. PrimeQD 83. In[60]:= Out[60]= Select@data. here we select those elements in this short list of integers that pass the EvenQ test. 22. 8x2 . In its simplest form.7434. c.7676. EvenQD 82. 2016 . 27. 8< This finds Mersenne numbers (numbers of the form 2n . In this section we will explore two additional functions that can be used for such tasks. True. but it is more general than just that. False. 29. 22. We have already seen how you can use Cases with patterns to express the criteria of interest. SelectAexpr. d. 20.1488. 5.7762< Pick can also be used to extract elements based on predicates.1488. you might want to filter out all numbers in an array outside of a certain range of values. 24.1331. inRange. b.1017/CBO9780511972942. 29. 4. z2 <D x1 x2 + y1 y2 + z1 z2 Select and Pick When working with data. 8n.1) that are prime. that returns True if its argument falls in a certain range. http://dx. 100<D. 9<. inRange@x_D := 20 § x § 30 Then select those elements from data that pass the test. Or you might need to find all numbers that are of a particular form or pass a particular test. 23. selListE picks those elements from expr whose corresponding value in selList is True . 8True. 22.4736. given an array of 27.39001. In[56]:= Out[56]= Select@81.1039.

1 Ø 5. 1 Ø 11. 2 Ø 9.006 Cambridge Books Online © Cambridge University Press. 0. 2 Ø 3. 1 Ø 6. 1 Ø 10. that is. For Pick . 4 Ø 5. 9 Ø 10. This list is then used to choose those edges whose corresponding probability is less than . 2 Ø 4. 4 Ø 10. 2 Ø 5. 6 Ø 9. 7 Ø 8. Downloaded from Cambridge Books Online by IP 157. 7 Ø 11. 1D 8a. c.2 Functions for manipulating expressions 127 You can also use binary values in the second argument. 1. 10 Ø 11< The number of edges in the complete graph grows quickly with n. 2 Ø 7.3 (you could choose any threshold between 0 and 1). In[64]:= Out[64]= edges = EdgeRules@CompleteGraph@11DD 81 Ø 2. e< Let us work through an example that is a bit more interesting. 2 Ø 11. 7 Ø 10. e<. but then you need to provide a third argument to Pick indicating that the selector value is 1. 3 Ø 5.50 on Wed May 18 01:16:10 BST 2016. 3 Ø 8. 1 Ø 9. 3 Ø 6. 4 Ø 7. 4 Ø 8. 1<.50. 3 Ø 4. 1 Ø 3. 6 Ø 11. In[62]:= Out[62]= Pick@8a. We will create a random graph and assign a probability to each edge. 4 Ø 6. 1 Ø 7. b. 2016 . 5 Ø 10. In[63]:= CompleteGraph@11D Out[63]= Here are the edges. 5 Ø 9. 8 Ø 11. using Pick . 8 Ø 9. 2D True We start by creating a list of probabilities consisting of random real numbers between 0 and 1. c. 5 Ø 8. 1 Ø 4. 81. 4 Ø 11. 6 Ø 8. 6 Ø 10. 8 Ø 10. We will start with the edges in a complete graph.1017/CBO9780511972942. 4 Ø 9. 5 Ø 11. http://dx. 3 Ø 7. 2-element subsets of a list of length n which is given by the binomial coefficient 2 In[65]:= Out[65]= Length@edgesD == Binomial@11.doi. this list and the list of edges must be the same length. 5 Ø 6. 3 Ø 10. a graph in which there is an edge between every pair of vertices. 6 Ø 7. 9 Ø 11. 7 Ø 9. Essentially we have a probability for each edge and we are choosing those edges whose corresponding probability value is below the threshold. Then. 1 Ø 8. d. 5 Ø 7. 2 Ø 10. we will include only those edges whose corresponding probability is less than some threshold value. 3 Ø 11. It is the same as the number of n . 2 Ø 8. 2 Ø 6. 3 Ø 9.

p = . 4 Ø 7. In[68]:= Out[68]= includedEdges = Pick@edges. 8 Ø 10< Finally.Functional programming 128 In[66]:= probs = RandomReal@1. 5 Ø 7.467768. 1 Ø 4. Graph@includedEdges. probs = RandomReal@1. 0.439899. GraphLayout Ø "CircularEmbedding"D Out[69]= Let us try this out with more vertices and a lower probability of an edge connecting any two. 1 Ø 10.006 Cambridge Books Online © Cambridge University Press.71338.940476< The third argument to Pick below is the pattern that the corresponding element of probs must match. pr_ ê. Binomial@11. 1 Ø 7. 7 Ø http://dx. 2 Ø 11. 2 Ø 8. pr < pD. 3 Ø 4. 0.1017/CBO9780511972942.253. 2DD. 0. 2016 . 4 Ø 5. probs. 2 Ø 9. 0.692795.3D 81 Ø 2.50. á46à. edges = EdgeRules@CompleteGraph@nDD. 0. 0. 6 Ø 7. 6 Ø 9. probs. GraphLayout Ø "CircularEmbedding"D Out[75]= Downloaded from Cambridge Books Online by IP 157. 6D Out[67]//Short= 80.100506. includedEdges = Pick@edges. Binomial@n.737098. 0. we turn this list of included edges into a graph. In[69]:= Graph@includedEdges. 5 Ø 6. 2DD.140067. 0. In[70]:= n = 100. 4 Ø 9.doi.50 on Wed May 18 01:16:10 BST 2016. 1 Ø 5. Short@probs. pr < .247101. pr_ ê.

a bit more work is needed to insure that our simple randomGraph always returns a graph with n vertices. pr < pD. Graph@includedEdges. edges = EdgeRules@CompleteGraph@nDD. pr_ ê. http://dx. In[77]:= n = 100.08. In[76]:= RandomGraph@BernoulliGraphDistribution@100. p = .org/10. probs. 0.1017/CBO9780511972942. although we used a uniform probability distribution (the default for RandomReal ) rather than running Bernoulli trials via a Bernoulli distribution.50 on Wed May 18 01:16:10 BST 2016. In addition.50. starting with an edge connecting every pair of vertices and then selects edges independently via a Bernoulli trial with probability pr. 2DD. Binomial@n. GraphLayout Ø "CircularEmbedding"D Out[82]= Downloaded from Cambridge Books Online by IP 157. this functionality is built into BernoulliGraphDistribution@n. in this next computation.08. probs = RandomReal@1. it does not take a very large probability threshold to significantly increase the likelihood that any two vertices will be connected.doi. 2016 .2 Functions for manipulating expressions 129 In fact.006 Cambridge Books Online © Cambridge University Press.253. includedEdges = Pick@edges.5. it is only .03D. GraphLayout Ø "CircularEmbedding"D Out[76]= This mirrors the construction of our random graph above. prD which constructs an n-vertex graph. As an aside.

86.50 on Wed May 18 01:16:10 BST 2016. 6<. 6  4. 0<. 6  0. http://dx. 86. An adjacency matrix can be thought of as representing a graph of vertices and edges where a value of 1 in position aij indicates an edge between vertex i and vertex j. Downloaded from Cambridge Books Online by IP 157. find the maximum distance between any pair of these points. 812. This is often called the diameter of the pointset. 86. 6  4. 84. 87. 1<. 5<D. 3  4< Make sure that your function also works in the case where its argument is a single list of a pair of elements. 7  6. 7  8. 2<.006 Cambridge Books Online © Cambridge University Press. whereas aij = 0 indicates no such edge between vertices i and j. 8<. 0<.50.1 to use Apply. 83.doi. Rewrite the definition of SquareMatrixQ given in Section 4. 4  0. you should get the following edge counts for the five vertices represented in the above adjacency matrix. 3<. 5. For example: In[4]:= Out[4]= In[5]:= Out[5]= lis = RandomInteger@9. 80. 7  1. 5< 4. In[1]:= mat = RandomInteger@1. Given a set of points in the plane (or 3-space). 2. 4<< ToGraph@lisD 84  3. 4  7. 3. 87. 84. 5  2. 85. 85. For example. Create a function ToGraphAlisE that takes a list of pairs of elements and transforms it into a list of graph (directed) edges. 4<.org/10. 7<.253. 2016 . 4<. 1<.1017/CBO9780511972942.Functional programming 130 Exercises 1. 0  1. 87. 83. MatrixForm@matD Out[2]//MatrixForm= 0 0 1 0 0 In[3]:= 0 0 1 1 0 0 1 1 1 0 1 1 0 0 1 1 0 1 0 1 AdjacencyGraph@mat. Note: self-loops count as two edges each. 7. 2<D 884. VertexLabels Ø "Name"D Out[3]= Compute the total number of edges for each vertex in both the adjacency matrix and graph representations. 4.

Create a function RandomColor@D that generates a random RGB color. Construct the Vandermonde matrix of order n. The divergence is given by the sum of the pairwise partial derivatives. 4<< and 8x.50. 11. 9. 10.2 Functions for manipulating expressions In[6]:= Out[6]= ToGraph@83. y< 8x + 2 y.50 on Wed May 18 01:16:10 BST 2016. 1<< Use Apply to reconstruct the original number from this nested list. matrix multiplication is a bit more involved. Use MapThread and Apply to mirror the behavior of Inner. is used. 83. vars = 8v1 . y< without using Dot. The Vandermonde matrix arises in Lagrange interpolation and in reconstructing statistical distributions from their moments. v2 . en < dependent upon n variables. 12. 6. varsD that computes the divergence of an n-dimensional vector field. 7. 3 x + 4 y< Perform matrix multiplication on 881. In[8]:= Out[8]= FactorInteger@3 628 800D 882. Consider using Thread or MapThread to thread Circle@…D across the lists of centers and radii. …. …. 83. 2<. 6<D 36 5. 2<.org/10. written as a single period. Use RandomColor from the previous exercise to give each circle a random color.8x. 8<. While matrices can easily be added using Plus . vn <. In[7]:= Out[7]= 881. 83. Create a function PrimeFactorForm@nD that formats its argument n in prime factorization form. which should look like the following: 1 x1 x21  xn-1 1 1 x2 x22  xn-1 2 ª ª ª  ª 1 xn x2n  xn-1 n 13.253. FactorInteger@nD returns a nested list of prime factors and their exponents for the number n. Using Inner. Create a graphic that consists of n circles in the plane with random centers and random radii. 2016 131 .doi. http://dx.1017/CBO9780511972942. e2 . vecs = 8e1 . Repeat the above exercise but instead use Inner to reconstruct the original number n from the factorization given by FactorInteger@nD. For example: In[9]:= Out[9]= PrimeFactorForm@12D 22 ÿ 3 1 You will need to use Superscript and CenterDot to format the factored integer. 85. 2<. 87. write a function div@vecs.006 Cambridge Books Online © Cambridge University Press. 8. Add a rule for RandomColor@nD to create a list of n random colors. Downloaded from Cambridge Books Online by IP 157. The Dot function. 4<<.5. 4<.

0.659983.73583. and many sciences is to repeatedly apply a function to some expression. and several types of numerical Cos@0.743904. In[1]:= Out[1]= Nest@g. we will introduce several functions available in Mathematica for function iteration. a.Functional programming 132  e1  v1 +  e2  v2 ++  en  vn 14.doi.85. In[2]:= Out[2]= NestList@g.703843. 0. 0.85.790003. the visualization of Julia sets. 5.85. and so on. 0. including Newton’s method.731902.85. 0. 0.76236. a. 0.253. Here. 2016 . Cos@Cos@0. Nest The Nest function is used to iterate functions.790003.85D.85DDD< 80.1017/CBO9780511972942. 0. 10D 80. 4D g@g@g@g@aDDDD NestList performs the same iteration but displays all the intermediate values.1 that are prime doing the computation for all exponents n from 1 to 100. 0. g is iterated four times starting with initial value a. http://dx.723208. 0.85DD. 4D 8a. The example in the section on Select and Pick found those Mersenne numbers 2n .741274< The list elements above are the values of 0. g@aD.85D. chaos theory. 0. In[4]:= Out[4]= 80. Modify that example to only use prime exponents (since a basic theorem in number theory states that a Mersenne number with composite exponent must be composite). Cos@Cos@0. this generates a list of ten iterates of the Cos function.85. In this section. 0.3 Iterating functions A common task in computer science. Cos@Cos@Cos@0.85. Another area. 0. rests on studying how iterated functions behave under small perturbations of their initial conditions or starting values. In[3]:= Out[3]= NestList@Cos. Iterating functions has a long and rich tradition in the history of computing with perhaps the most famous example being Newton’s method for root finding. In later chapters we will apply these and other programming constructs to look at some applications of iteration. mathematics.659983.85DD. g@g@aDD.749687. g@g@g@g@aDDDD< Using a starting value of 0.50 on Wed May 18 01:16:10 BST 2016.50. Cos@0. 0.006 Cambridge Books Online © Cambridge University Press. g@g@g@aDDD.703843< Downloaded from Cambridge Books Online by IP 157.

Graphics@triD Out[8]= This creates a function that we will iterate inside Nest . otherwise you can easily generate many pages of symbolic output on your screen. 81. 18DD Out[10]= Downloaded from Cambridge Books Online by IP 157. rotation takes a graphical object and rotates it p ê 13 radians about the point 81. be careful to keep the iteration count manageable.5. http://dx. 3 í 2>>. In[6]:= In[7]:= vertices = :80.85D. suppose we had a triangle in the plane that we wanted to rotate iteratively. a<D. 1<D Here are eighteen steps of this iteration.006 Cambridge Books Online © Cambridge University Press. tri = Line@vertices ê. cos@cos@cos@0.3 Iterating functions 133 Using a lowercase symbol cos. 1<. b_< ß 8a. the rule 8a_. b__< ß 8a. here is a display of the starting triangle. 0<.85. 2016 . Starting with a set of vertices. p ê 13. In[5]:= Out[5]= NestList@cos. Although this is a useful tip for helping you to see the structure of such computations.85DDD< The objects that you can iterate are entirely general – they could be graphics. :1 ê 2.50. 8a_. 0<. For example.253. a< is used to copy the first point in vertices to the end of the list.85. 3D 80. cos@0. To close up the figure. you can see the symbolic computation clearly. b.doi. 0.85DD. b. In[10]:= Graphics@NestList@rotation.1017/CBO9780511972942.50 on Wed May 18 01:16:10 BST 2016. tri. In[9]:= rotation@gr_D := Rotate@gr. 81.

tri.50 on Wed May 18 01:16:10 BST 2016. In[11]:= Out[11]= vecs = 1 ê 2 vertices 1 1 :80.253.1017/CBO9780511972942.0D. 2016 . http://dx. here is a function that. the Sierpinski triangle. For example. 1. use FixedPoint . This function is particularly useful when you do not know how many iterations to perform on a function whose iterations eventually converge. you can see all the intermediate results.Functional programming 134 Or you can iterate a translation.doi. Downloaded from Cambridge Books Online by IP 157. FullForm shows all digits computed. vecsD In[13]:= Graphics@8Blue. In[12]:= translation@gr_D := Translate@gr. Here we display every third element in the list. 2 4 3 4 >> The translation function creates three objects translated by the vectors vecs. create some translation vectors. In[16]:= phi = FixedPointList@golden. gives a fixed point for the Golden ratio. 1 In[14]:= golden@f_D := 1 + f In[15]:= Out[15]= FixedPoint@golden. a point x such that x = cosHxL. 3D<D Out[13]= The exercises at the end of this section build upon these ideas to create a more interesting and well-known object. that is. FixedPoint In the example of the cosine function from the previous section. when iterated. : . : . 0<. the iterates converge to a fixed point. To apply a function repeatedly to an expression until it no longer changes.006 Cambridge Books Online © Cambridge University Press.61803 Using FixedPointList . First. 0>. NestList@translation. making it easier to see the convergence.0D 1.

0. we stop the iteration when two successive iterates differ by less than 10-10 .6180339631667064`.618033988749894`D Sometimes.006 Cambridge Books Online © Cambridge University Press.1017/CBO9780511972942.50.6666666666666665`. 2016 . 1.6.85. 1. 100D 0.618034447821682`. 1. SameTest Ø IAbs@Ò1 .6180257510729614`.6180339887496482`.6180339886704433`.3.) In[20]:= Out[20]= FixedPointACos.253.739085 NestWhile The Nest function iterates a fixed number of times. 1. In[21]:= addOne@n_D := n + 1 In[22]:= CompositeQ@n_Integer ê. 1..6180339887499087`. n > 1D := Not@PrimeQ@nDD Downloaded from Cambridge Books Online by IP 157. either you can give an optional third argument to indicate the maximum number of iterations to perform or you can specify a looser tolerance for the comparison of successive iterates. NestWhile (or NestWhileList) is perfect for this. using CompositeQ from Exercise 5 of Section 2. In[19]:= Out[19]= FixedPoint@Cos. on pure functions.6180339901755971`. the iteration does not converge quickly and you need to relax the constraint on the closeness of successive iterates. 1. 5D $Aborted In such cases. For example. 3DD êê FullForm Out[17]//FullForm= List@1. 0.Ò2D < 10-10 &ME 0. 1. whereas FixedPoint iterates until a fixed point is reached.3 Iterating functions In[17]:= 135 phi@@1 . the cosine function has a fixed point but there is some difficulty converging using the default values for FixedPoint . (We will discuss the odd notation involving # and & in Section 5. In[18]:= Out[18]= TimeConstrained@ FixedPoint@Cos.85. here we find the next prime after a given number. 0.50 on Wed May 18 01:16:10 BST 2016. 1. http://dx.739085 In the following computation. Sometimes you want to iterate until a condition is met. -1 .6180339887543225`.85D. 1.6181818181818182`. For example.5.6153846153846154`.doi. 1.`. 1..

Functional programming



NestWhileAaddOne, 2100 , CompositeQE
1 267 650 600 228 229 401 496 703 205 653

Verify with the built-in function that computes the next prime after a given number.
In[25]:= NextPrimeA2

1 267 650 600 228 229 401 496 703 205 653

Whereas Nest and NestList operate on functions of one variable, Fold and FoldList
generalize this notion by iterating a function of two arguments. In the following example, the
function f is first applied to a starting value x and the first element from a list, then this result is
used as the first argument of the next iteration, with the second argument coming from the
second element in the list, and so on.

Fold@f, x, 8a, b, c<D
f@f@f@x, aD, bD, cD

Use FoldList to see all the intermediate values.

FoldList@f, x, 8a, b, c<D
8x, f@x, aD, f@f@x, aD, bD, f@f@f@x, aD, bD, cD<

It is easier to see what is going on with FoldList by working with an arithmetic operator. This
generates “running sums.”

FoldList@Plus, 0, 8a, b, c, d, e<D
80, a, a + b, a + b + c, a + b + c + d, a + b + c + d + e<
FoldList@Plus, 0, 81, 2, 3, 4, 5<D
80, 1, 3, 6, 10, 15<

The built-in Accumulate function also creates running sums but it does not return the initial
value 0 as in FoldList .

Accumulate@81, 2, 3, 4, 5<D
81, 3, 6, 10, 15<

Downloaded from Cambridge Books Online by IP on Wed May 18 01:16:10 BST 2016.
Cambridge Books Online © Cambridge University Press, 2016



1. Determine the locations after each step of a ten-step one-dimensional random walk. (Recall that
you have already generated the step directions in Exercise 3 at the end of Section 3.1.)
2. Create a list of the step locations of a ten-step random walk on a square lattice.
3. Using Fold , create a function fac@nD that takes an integer n as argument and returns the factorial
of n, that is, nHn - 1L Hn - 2L 3 ÿ 2 ÿ 1.
4. The Sierpinski triangle is a classic iteration example. It is constructed by starting with an equilateral
triangle (other objects can be used) and removing the inner triangle formed by connecting the
midpoints of each side of the original triangle.


The process is iterated by repeating the same computation on each of the resulting smaller triangles.




One approach is to take the starting equilateral triangle and, at each iteration, perform the appropriate transformations using Scale and Translate , then iterate. Implement this algorithm, but be
careful about nesting large graphical structures too deeply.

5.4 Programs as functions
A computer program is a set of instructions (a recipe) for carrying out a computation. When a
program is evaluated with appropriate inputs, the computation is performed and the result is
returned. In a certain sense, a program is a mathematical function and the inputs to a program
are the arguments of the function. Executing a program is equivalent to applying a function to its
arguments or, as it is often referred to, making a function call.

Building up programs
Using the output of one function as the input of another is one of the keys to functional programming. This nesting of functions is commonly referred to by mathematicians as “composition of
functions.” In Mathematica, this sequential application of several functions is sometimes referred
to as a nested function call. Nested function calls are not limited to using a single function repeatedly, such as with the built-in Nest and Fold functions.

Downloaded from Cambridge Books Online by IP on Wed May 18 01:16:10 BST 2016.
Cambridge Books Online © Cambridge University Press, 2016

Functional programming


As an example, consider the following expression involving three nested functions.

Total@Sqrt@Range@2, 8, 2DDD

2 +


This use of functions as arguments to other functions is a key part of functional programming,
but if you are new to it, it is instructive to step through the computation working from the inside
out. In this computation, the Mathematica evaluator does the computation from the most deeply
nested expression outward. The inner-most function is Range and it produces a list of numbers
from 2 through 8 in steps of 2. Moving outwards, Sqrt is then applied to the result of the Range
function to produce a list of the square roots. Finally, Total adds up the elements in the list
produced by Sqrt .

Range@2, 8, 2D
82, 4, 6, 8<


9 2 , 2,





2 +




Wrapping Trace around the computation shows all the intermediate expressions that are used
in this evaluation.

Trace@Total@Sqrt@Range@2, 8, 2DDDD
998Range@2, 8, 2D, 82, 4, 6, 8<<,
9 2,


9 6,

6 =, 9 8 , 2


TotalA9 2 , 2,

8 =, 9 2 ,


82, 4, 6, 8< ,

2 =, 9 4 , 2=,

2 =, 9 2 , 2,
2 =E, 2 + 3


2 +

2 ==,


You can read nested functions in much the same way that they are created, starting with the
innermost functions and working towards the outermost functions.
listEvenQ As another example, the following expression determines whether all the elements in a
list are even numbers.

Apply@And, Map@EvenQ, 82, 4, 6, 7, 8<DD

Let us step through the computation much the same as Mathematica does, from the inside out.
Start by mapping the predicate EvenQ to every element in the list 82, 4, 6, 7, 8<.

Downloaded from Cambridge Books Online by IP on Wed May 18 01:16:10 BST 2016.
Cambridge Books Online © Cambridge University Press, 2016

8<D. 83. 3. Max@7. 3. 3. we return to a computation done with rules in Chapter 4 – returning the elements in a list of positive numbers that are bigger than all the preceding numbers in the list. False. 0. 6<D Out[11]= False maxima In the next example. 6<. 5D. 16. 7<DDD 83. 3<. 7<. 1. 8Max@8. 1. True. 8Max@6. 6. 4. 8<<. 6. 6. 3. 0.253. 8. 8Max@6. 6D. 8< 6. 8. 6. 4.4 Programs as functions In[7]:= Out[7]= 139 Map@EvenQ. 0.006 Cambridge Books Online © Cambridge University Press. Protected< Finally. 8. 1. DeleteDuplicates@80. 5. 0. In[13]:= Out[13]= Trace@Rest@ DeleteDuplicates@FoldList@Max. 5. 8. 6D. True. 6. 8< Tracing the evaluation shows the intermediate steps of the computation. EvenQ@lisDD In[11]:= listEvenQ@811. 8Max@6. 4. 6. 83. In[10]:= listEvenQ@lis_D := Apply@And. here is a definition that can be used on arbitrary lists. 83. 83. 6. 6. %D False Actually. 8. 83. 3D. 8D. 80. In[8]:= Out[8]= Apply@And. 1. 6<. 3D.50. http://dx. 8Max@3. 8. 80. 18. 5. 8Max@3. 0. 8<D 8True. 2016 . Rest@80. 6. 4. 5. 1D. Look at the Trace of this computation to see what FoldList is doing here. True< Apply the logical function And to the result of the previous step. 3. 4. 8<. 5. 8<. 1. and the list 83. 6. 3<. 6. 7<D 80. Max@4. 7<D.50 on Wed May 18 01:16:10 BST 2016. EvenQ has the Listable attribute – it automatically maps across lists and so this computation can be shortened a bit. 7D. 17. 7<DDDD 888FoldList@Max.1017/CBO9780511972942. 6<. 8D. 7. 3. In[14]:= Out[14]= FoldList@Max. 6. 3. In[12]:= Out[12]= Rest@DeleteDuplicates@FoldList@Max. 8. 82. 6D. 6.5. Max@1. 8<< FoldList is first applied to the Max. 4D. Max@5. 6. 4. 8< Downloaded from Cambridge Books Online by IP 157. 8Max@0. 8. In[9]:= Out[9]= Attributes@EvenQD 8Listable. 6. 6. 6. 6. 6.doi. 3. 1. 8<<. 5.

8´. etc. <. 7. 5<. This is to avoid the possibility that these symbols may have rules associated with them that would interfere with our intent here. 3. 9<. 8®. 8©.50. 11. K already has meaning – it is a built-in symbol. 9<. . 8®. 10<. 9. 1D 88®. In[17]:= maxima@lis_D := Rest@DeleteDuplicates@FoldList@Max. 8´. 8´. <. 4. 9. queen. 8™. 7<. 4<. 8©. 10D. 8©. 8®. 8™. lisDDD Applying maxima to a list of numbers produces a list of all those numbers that are larger than any number that comes before it. <. <. K.Functional programming 140 DeleteDuplicates is then applied to the result of the previous step to remove the duplicates. 14. << The suit icons are entered by typing in \[ClubSuit]. 8®. 8®. In[19]:= Out[19]= cardDeck = Flatten@Outer@List. 8©. 7.. and ace rather than the plain symbols J. 7<. \[DiamondSuit]. 8<. 8©. 8´. 8™. 4<. <. 8©. 2. <. 8®. 8<. 8™. 8®. 8´. In[16]:= Out[16]= Rest@%D 83. or by using one of the character palettes built into Mathematica. 8™. 5<. 14. 7<. <. 8®. ´<. 8´. <DD. 9<. 8™. 3<. 6<. and A. <. 8©. <. 7<. 9<. Rest is applied to the result of the previous step to drop the first element. 8®. 8´. 2<. 8´. 3<. 3<. In[20]:= ?K K is a default generic name for a summation index in a symbolic sum. In[15]:= Out[15]= DeleteDuplicates@%D 80. 3. We have used special characters to represent the jack. king. 4<. 17< Example: shuffling cards Here is an interesting application of building up a program with nested functions – the creation and shuffling of a deck of cards. Q. 5<. ™.org/10. 3<. Join@Range@2. ©. http://dx. 2<. 8©. <. 4<. 6. 8©. <. 8©. . 5<.doi. 8 . <. 8©. 2<. 8©. 8™. 8™. 8´. 8™. 0. 8<. 2016 . 8™. <.50 on Wed May 18 01:16:10 BST 2016. In[18]:= Out[18]= maxima@84. 0. 8´.006 Cambridge Books Online © Cambridge University Press. 8´. 8< Finally. 8™. 8®. 8< Here is the function definition. You might think of cardDeck as a name for the expression given on the right-hand side of the immediate definition. 8©. 8™. 6<. 8<. In fact. 10<. 8´. 2<. 10<. <. 17<D 84. 8®. 8®. 8™. 6<. or you might think of cardDeck as defining a function with zero arguments. 6<. 8®. 6. Downloaded from Cambridge Books Online by IP 157.1017/CBO9780511972942. 10<. <.253. 8´.

8™. 8 .1017/CBO9780511972942. We therefore unnest the list. 5<. 8™. 8®. 8™. 8©. 8´. 6. 8´. with a four-element list representing the jack. <. 8©. 8®. 2016 . 9. 8©. 8™. 8™. 3<. 8™. << Voila! The step-by-step construction used here. <. 8´. 8®. In[21]:= Out[21]= Join@Range@2. 8©. 8´. 8™. consisting of cutting the deck in half and then interleaving the cards from the two halves. 8´. 6<. we will build up this program from scratch. 8®. This produces a list of 52 ordered pairs representing the cards in a deck. <. 8´. 7<. 8´. 8©. 8®. 8®. 6<. checking each function call separately. 8™. 4<. 4<. <D 82. 9<. 8®. 8™. <. . <. <). 8©. 10<. 4<. 8™. 8©. 3<. Rather than working with the large list of 52 ordered pairs during the prototyping. 5. is a very efficient way to prototype your programs in Mathematica. 8™. 7.4 Programs as functions 141 To understand what is going on here. 3<. 8´. 8´. 8™. 8©. 8®. 6<. <. 8®. In[23]:= Out[23]= Flatten@%. 10D. where the king of clubs. 3<. 88´. 8©. 4<. 8´. 88™. 4<. 2<. We will use this technique again in many subsequent examples. . . <. 2<. 8©. working from the inside out. 7<. 8™. 8<. <. 9<. <. 8´. 4<. <. 8©. 8™. 7<. 88©. <. 8™. 8´. 8®. applying one function at a time. 3. 8®. 8©. 8™. <. ©. 8<. <. http://dx. 2<. 8™. 8´. let us perform what is called a perfect shuffle. 8®. 3<. 8<. 9<. 8©. 8©. 10<. 7<. <<< While we now have all the cards in the deck. . 5<. 8™. 8´. 8©. and ace. 8©. they are grouped by suit in a nested list. 8. 8´. <<. 8©. 8©. 5<. 10<. 8®. we form a list of the number and face cards in a suit by combining a list of the numbers 2 through 10. 10<. <. ´<. 8®. <. we will use a short list of an even number of ordered integers. 4<. 10<. ™. <. First.5. 7<. 8<. <. 8™. 8´. 4<. <. In[22]:= Out[22]= Outer@List. 8©. 2<. <. 8®. 6<.50. 8®. 8. <. queen. <<. 8´. 8´. 8™. <. 8©. Downloaded from Cambridge Books Online by IP 157. 8´. 9<. 8®.253. 8®. 2<. 8´. . 1D 88®. 8®. 8™. ´<. <. 8®. 8©. 9<. 8<. 7<. . 5<. 8®.50 on Wed May 18 01:16:10 BST 2016. 8©. 10<. .006 Cambridge Books Online © Cambridge University Press. 8©. 8™. <. 5<. 8´. 3<. 10<. 8®. 8®. <<. ©. 2<. 8©. 5<. 8™. 6<. 8<. <. king. 8®. 10<. 5<. 9<. 9<. is represented by 8®. 9<.doi. <. 2<. 8™. 8™. 10. 3<. Next. <. 8´. 8©. 8<. 7<. 7<. 2<. 6<. 5<. 3<. 8´. %D 888®. for example. < Next we pair each of the 13 elements in this list with each of the four elements in the list representing the card suits 8®. 8<. <. <.org/10. 6<. ™. 8´. 6<. 8´. 8®. 4.

2. <. 8™.1017/CBO9780511972942. <. 6<< Apply@Riffle. In[30]:= shuffle@8a. this can be corrected by Downloaded from Cambridge Books Online by IP 157. <. 8®.253. 2<. 8´. 7<. 6<. In this case. 8´. 8™. 8®. 8™. we are using code that will generalize to arbitrary inputs. 8©. 5<. 8®. 7<. 3.50 on Wed May 18 01:16:10 BST 2016. 4. <. Partition@lis. 8´. 8™. 8™. 8´. 4<. 8´. <. 10<. 8©. 8™. 8©. 10<. 7<. 3<. 2 5 . 8©. <. e<D Partition::ilsmp : Single or list of positive machine-sized 5 integers expected at position 2 of PartitionB8a. 8´. <. 2<. 8©. 5. 2 Out[30]= :a. e<. 5 5 . 7<. 8®. 9<. 8<. 2. 8©. 8®.50. 8®. 4. <. 6<D Out[28]= In[29]:= Out[29]= 81. 9<. %D 81. 6< That does the job. e> 2 This is not an uncommon situation when writing programs: after some prototyping and writing of code to solve the problem. 2. 6< shuffle@cardDeckD 88®. 8™. one of those scenarios pointed up a deficiency in our program. 8©. 8©. 8®. 5. 5. 8<.Functional programming 142 In[24]:= Out[24]= lis = Range@6D 2. 8©. 8®. 8®. 8©. 3. 4<. 5<. 6< First divide the list into two equal-sized lists and then apply the built-in Riffle function which interleaves two lists.006 Cambridge Books Online © Cambridge University Press. 10<. Given this prototype. 8´. 4<. à . 9<. 6<. That is. 2 5 . Notice that even with this simple prototype. <. 2 F. http://dx. 9<. 6<. <. 8™. 8™. 6<. 5. b. 2<. 84. if you are thorough. 8´. 8™. 8®. 5<. << Unfortunately. 2016 . here is a function to perform a perfect shuffle on a deck of cards. 4<. 4. Length@lisD ê 2DD In[28]:= shuffle@81. 5. 4. 2<. In[27]:= shuffle@lis_D := Apply@Riffle.doi. <. you try it out on various inputs and. Length@lisD ê 2D 881. d. c. 3. In[25]:= Out[25]= In[26]:= Out[26]= Partition@lis. 8©. 8®. 8©. we let Mathematica compute the length. 8™. b. this definition for shuffle does not properly handle lists of odd length. d. 8™. d. 2. 3<. 8®. 8<. 3<. 8´. 3<. 8´. rather than give 3 as the second argument to Partition here. c. <. 3<. 5<. 8´. 8<. 8´. b. <. <. 8™. c. <. 10<. 8´. you cover all the possible situations that your program was designed to take into account. 8©. 3. Fortunately.

The third argument. 2. n. …. The second argument. nD In[36]:= deal@5D Out[36]= 88´. len. <. 4. When a compound function is evaluated with particular argument values. 2016 . expr2 . compound functions. for example. 3<. The fourth argument.50. len. 4. The right-hand side consists of expressions enclosed in parentheses. the definition of cardDeck must be entered before calling deal. This can be done using compound function definitions. 5. The left-hand side of a compound function is the same as that of a user-defined function.doi. d. 8©. d. treats the lists as cyclic. the expressions on the right-hand side are evaluated in order and the result of the evaluation of the Downloaded from Cambridge Books Online by IP 157. 5<. 8<DDD shuffle@81. is the list on which we are operating. 2. exprm L The expressions expri can be any expression: a simple value assignment or a user-defined function. In[35]:= deal@n_D := RandomSample@cardDeck.253. 8©. Since we want to take into account lists of odd length. To use deal. we also use Ceiling to get an integer value for len. 5<D 81. 8<E The first argument given to Partition. 2. which randomly chooses without replacement. 2. 4. In[31]:= In[32]:= In[33]:= Out[33]= In[34]:= Out[34]= Clear@shuffleD shuffle@lis_D := Module@8len = Ceiling@Length@lisD ê 2D<. << Compound functions There are several major drawbacks to the above approach to dealing cards. http://dx. Partition@lis. Apply@Riffle. 6<D on Wed May 18 01:16:10 BST 2016. 8™. argn _D := Hexpr1 . or simply. And the fifth argument. It would be much more convenient if we could incorporate this function within the deal function definition itself. allows for no padding so the lists can be of unequal length.006 Cambridge Books Online © Cambridge University Press. 1. 6< An obvious thing to do with a deck of cards is to deal them! Simply use RandomSample . 5. 1. 4. 8™. separated by semicolons. 8<. n. 3. arg2 _. 3. PartitionAlist. …. gives the offset: in this case no overlap by setting this argument to the same value as the size of the sublists. name@arg1 _. 1. <. lis.1017/CBO9780511972942. 3< shuffle@81. 5. gives the size of the sublists. 3.4 Programs as functions 143 making a few minor modifications including the use of a different argument structure for Partition.5.

1D. 10D. . 8™. 8®. 8 . note the use of parentheses wrapped around the compound expressions (those separated by semicolons). nD L Let us check that this works.006 Cambridge Books Online © Cambridge University Press. the display of the final evaluation result can also be suppressed).org/10. In[40]:= deal@n_D := H cardDeck = Flatten@Outer@List. 8®. In[37]:= cardDeck = Flatten@Outer@List. Join@Range@2. first remove the old definitions. In[41]:= Out[41]= deal@5D 88´. ™. <. 2016 . 8®. ™. nD To convert to a compound function. deal@n_D := RandomSample@cardDeck. ©. We will work with the deal function to illustrate how a compound function is created. when you evaluate a compound function definition. 8 .1017/CBO9780511972942. the auxiliary function definitions and value declarations remain. This can cause a problem if you subsequently try to use the names of these auxiliary functions and values elsewhere. 8™. Again. << Several things should be pointed out about the right-hand side of a compound function definition. Join@Range@2. 8®. 1D. . <DD. This is a bit of an inconvenience that we will deal with more effectively in the next section on scoping constructs. Each time the Downloaded from Cambridge Books Online by IP 157. Since the expressions on the right-hand side are evaluated in order. Secondly. http://dx. . ©. . Finally. Here is a compound expression consisting of two inputs. ´<. Mathematica would think the function definition ended at the first semicolon. 4<. 10D. <DD.253. separated by a semicolon. If you then remove the function definition using Clear .50.doi. a rewrite rule corresponding to the entire definition is created. ´<. value declarations and (auxiliary) function definitions should be given before they are used and the argument names used on the left-hand side of auxiliary function definitions must differ from the argument names used by the compound function itself. you are creating not only the function but also the auxiliary functions and the value declarations. 8<.Functional programming 144 last expression is returned (by adding a semicolon after exprm .50 on Wed May 18 01:16:10 BST 2016. this issue will be addressed in the next section on scoping constructs. <. RandomSample@cardDeck. In[39]:= Clear@deal. How does the global rule base treat compound functions? When a compound function definition is entered. If you omitted the parentheses. cardDeckD Now create and enter the new definition.

a. In[42]:= ? cardDeck Global`cardDeck cardDeck = 88®. here are five random samples from the integers 0 through 9. 8©. 8©. 4<. 10<. so this is essentially random sampling with replacement. 8´.50. 5<. 8©. 8®. Many lotteries include games that require you to pick several numbers and match them against the “house. The built-in RandomChoice does this. 8™. 12D 8g. a< 5. 5<. you can localize their names by using the Module construct in the compound function definition. 8™. 5D 84. Here is a typical result using a list of symbols. 8©. 8™.1017/CBO9780511972942. 2<. 8®. Rewrite the listEvenQ function from this section using MemberQ . a. <. 3<. 8´. 8©. 8®. <. it could interfere with a user’s workspace and cause unintended problems. <. Exercises 1. In[2]:= Out[2]= randomChoice@8a. 8<. 8™. 8®. 8®. 8<. <. 3. 8©. In fact. h. 7<. Using the shuffle function developed in this section. 5<. 8™. 8´. 2016 . b.4 Programs as functions 145 compound function is subsequently called. In[1]:= Out[1]= RandomChoice@Range@0. 10<. << It is considered bad programming practice to leave auxiliary definitions in the global rule base if they are not explicitly needed by the user of your function.2 and maxima developed in this section to explain why the functional version is much faster than the pattern matching version. 4<.006 Cambridge Books Online © Cambridge University Press. 5<. 8´. h<. <. <. 9<. For example. 8™. 8. 3<. c. 8´. 8´. 8´. 8®. 3<. 8®. 4<. f. 8©. 8®. 8™. e. g. d. 8´. 4< Write your own function randomChoiceAlis. 10<.50 on Wed May 18 01:16:10 BST 2016. where n is the number of elements being chosen from the list lis. Using Total. 6<. 8´. 8´. Use Trace on the rule-based maxima from Section 4. c.” The numbers are independent. 8®. http://dx. 7<. rewrite rules are created from the auxiliary function definitions and value declarations within the compound function. 7<. 10<. 7<. <. 9D. 8™. 1. create a function to sum the first n positive integers. 9<. a. 8´. 4<. 2<. 8™. 7. <. 8<. 8<. 8©. 9<. This is discussed in the next section. 3<. 8©. <. <. <. 2. 8®. nE that performs a random sampling with replacement.doi. 8™. 8©. 8®. <. c. how many shuffles of a deck of cards (or any list. f. 8´. 6<. 8®. 2<. 8©. <. 2<. 8©.org/10. 8™. 8™. <. 6<. 9<. Downloaded from Cambridge Books Online by IP 157. d. 8™. 8©.253. 8´.5. c. To prevent these additional rewrite rules from being placed in the global rule base. for that matter) are needed to return the deck to its original order? 4. <. c. 6<.

50 on Wed May 18 01:16:10 BST 2016. If you wish. localizing the auxiliary symbol cardDeck. name2 = value. Write a function interleave that interleaves the elements of two lists of unequal length.006 Cambridge Books Online © Cambridge University Press. 3< as inputs and return 8a. as is shown with name2 above.50.253. body_of _function E The first argument of Module is a list of the symbols to be localized. b. In[1]:= Clear@deal. c. the assigned value is only an initial value and can be changed subsequently. …. b. .5 Scoping constructs Localizing names: Module When you define functions using assignments. Let us use Module to rewrite the deal function from the previous section. it is generally a good idea to isolate the names of values and functions defined on the right-hand side from the outside world in order to avoid any conflict with the use of a name elsewhere in the session (for example. .Functional programming 146 6. 8. 8 .) Your function should take the lists 8a. cardDeck from the previous section might be used elsewhere to represent a pinochle deck). 2. 7. 10D. …=. Write your own user-defined functions using the Characters and StringJoin functions to perform the same operations as StringInsert and StringDrop. http://dx. nDD Downloaded from Cambridge Books Online by IP 157. arg2 _. ©. c.doi. cardDeckD In[2]:= deal@n_D := Module@8cardDeck<. Join@Range@2. name@arg1 _. argn _D := ModuleA9name1 . 2. 2016 . 5. d<.org/10. ´<. RandomSample@cardDeck. cardDeck = Flatten@Outer@List. (You have already seen how to interleave lists of equal length using Partition earlier in this section with the shuffle function. 1. <DD. d< and 81. This localization of the variable names is done by wrapping the right-hand side of the function definition with the Module function.1017/CBO9780511972942. 8®. 3. The list of variables to be localized is separated from the righthand side by a comma and so the parentheses enclosing the right-hand side of a compound function are not needed. 1D. ™. Write nested function calls using ToCharacterCode and FromCharacterCode to perform the same operations as the built-in StringJoin and StringReverse functions. you can assign values to these names.

. 5<<. 3. these unique and temporary names. 3.<<. 5. 2. the local variable tmp has been renamed tmp$1532. 55. Module@8tmp = Range@5D<. you will need to localize a value associated with a symbol without localizing the symbol name itself.<.5 Scoping constructs In[3]:= Out[3]= 147 deal@5D 88©.. 2.. 4.tmpD. 55. 4.<<. 5. 8©. a unique and new name. 3. Localizing values: Block Occasionally. 2.tmpD In[5]:= f@5D Out[5]= In[6]:= Out[6]= 55. 2. 88tmp$1532.. 5<<. 3.50 on Wed May 18 01:16:10 BST 2016.81. 5<..<<.. showing some of the internals... 4.tmp$1532.. 8Range@5D.50. 2. 4. 4.. tmp. To see how Module works we’ll trace a computation involving a simple function. 2.. 81.1017/CBO9780511972942.. 2. N@81.doi..006 Cambridge Books Online © Cambridge University Press. 8©. 5. 4. 5<.. tmp$1532 = 81..<<. 5..< Looking at the trace. It is generally a good idea to wrap the right-hand side of all compound function definitions in the Module function. 8tmp$1532.5. 81. For example.. 10<< Briefly. 81. 81. which are local to the function. Trace@f@5DD 8f@5D. <. 5<D. 3.. 5. In[4]:= f@n_D := Module@8tmp = Range@nD<. the local variable will not interfere with any global variable whose name is tmp.. thereby only localizing the value of $RecursionLimit during the evaluation inside Block . 2. tmp = N@tmpD.<... 5. you may have a recursive computation that requires you to temporarily reset the system variable $RecursionLimit . 3. 55. 8©. 7<. 3.<. 3. 5. 888tmp$1532. tmp. when Module is encountered. Block has the same syntax as Module.. In this way.. tmp$1532. 4. Such functions are called pure functions and are discussed in Section 5. http://dx. the symbols that are being localized (cardDeck in the above example) are temporarily given new and unique names. 8´. 2.<. 5<<. 2016 .. In this way. and all occurrences of those symbols in the body of the Module are given those new names as well. You can do this with Block . will not interfere with any names of functions or values outside of the Module. 8tmp$1532 = N@tmp$1532D.6. 4. 8<. 4. 4.. 81. 2.. 2. 81. tmp = N@tmpD. 3. Downloaded from Cambridge Books Online by IP 157.. 81. 2. 3.<. 3. 4.. 81. 8tmp$1532 = 81. 3. Another way to avoid conflicts between the names of auxiliary function definitions is to use a function that can be applied without being given a name.253.

Block only affects the values of these symbols. In[13]:= y Out[13]= 5 Downloaded from Cambridge Books Online by IP 157. In[8]:= Out[8]= $RecursionLimit 256 Module. Here is a simple function that initializes y as a local constant. creates an entirely new symbol. In general you would not want to set these variables globally. Log@1000000`10DD Out[9]= 13. In[12]:= f@x_D := With@8y = x + 1<.50. This sets the global variable y to have the value 5. In[9]:= Block@8$MaxPrecision = 10. Localizing constants: With Another scoping construct is available when you simply need to localize constants. in the body of your function.50 on Wed May 18 01:16:10 BST 2016. on the other hand.006 Cambridge Books Online © Cambridge University x = g@xDD $RecursionLimit::reclim : Recursion depth of 20 exceeded. $RecursionLimit$nn that has nothing to do with the global variable $RecursionLimit . and Product . Block is used to localize the iterators in Table . http://dx. not their names. Do .doi. yD We see the global symbol is unchanged and it does not interfere with the local symbol y inside of With . In[11]:= y = 5.253.Functional programming 148 In[7]:= Block@8$RecursionLimit = 20<. and so Module would be inappropriate for this particular task. If. $MinPrecision = 10<. Sum .1017/CBO9780511972942. As another example. 2016 . we will do a computation with fixed ten-digit precision by setting the two system variables $MaxPrecision and $MinPrecision to 10. then With is the preferred means to localize that constant. you use a variable that is assigned a constant once and never changes.81551056 In[10]:= Precision@%D Out[10]= 10. In fact. à Out[7]= g@g@g@g@ g@g@g@g@g@g@g@g@g@g@g@g@g@g@Hold@g@xDDDDDDDDDDDDDDDDDDDD Notice the global value of $RecursionLimit is unchanged.

With is used here to temporarily set the value of n. n<.006 Cambridge Books Online © Cambridge University Press.253.1017/CBO9780511972942. 0D.tmpD Downloaded from Cambridge Books Online by IP 157. tmp. 1. 8i. that is. In[16]:= In[17]:= UpperTriangularMatrix@n_D := Table@If@j ¥ i. In[15]:= With@8n = 5<. For example. 8j. n<.5 Scoping constructs In[14]:= Out[14]= 149 f@2D 3 With is particularly handy when you want to perform a computation and experiment with some values of your parameters without setting them globally. symbols whose values do not change in the body of your functions – you will see some speed improvements. n<D D êê MatrixForm Out[15]//MatrixForm= 1 0 0 0 0 1 1 0 0 0 1 1 1 0 0 1 1 1 1 0 1 1 1 1 1 The advantage of this approach is that it is extremely easy to turn this into a reusable function.50 on Wed May 18 01:16:10 BST 2016. 1. the matrix will have 1s on and above the diagonal. http://dx. In[18]:= f1@n_D := Module@8tmp = NüRange@nD<. a matrix with 0s below the the size of the matrix. 8j. n<D UpperTriangularMatrix@6D êê MatrixForm Out[17]//MatrixForm= 1 0 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 1 1 1 0 1 1 1 1 1 1 Finally. Copying and pasting the line of code starting with Table@…D essentially gives the right-hand side of the function definition without the need to modify any parameters.doi. it should be noted that With is generally faster than Module. Table@If@j ¥ i. suppose you are prototyping code for a function that returns an upper triangular matrix. so if you are really working with local constants – that is.50. 8i. In the following example. 2016 . 0D.5.

doi. 3.006 Cambridge Books Online © Cambridge University Press. 2. Let us prototype with a small 5ä5 matrix. mat@@3DD< = 8mat@@3DD. 85. Downloaded from Cambridge Books Online by IP 157. 9105 =E E Out[21]= List component assignment is a destructive operation.253. 5.513982. As seen in the solution to Exercise 4 in Section 3.50 on Wed May 18 01:16:10 BST 2016. http://dx. tmp.Functional programming 150 In[19]:= TimingA DoAf1@100D. 9<< The problem with this approach is that mat is changed by the assignment. In[25]:= Out[25]= 8mat@@2DD.1017/CBO9780511972942. mat@@2DD< 888. say rows 2 and 3. 8.3. In[22]:= SeedRandom@123D. 9. 6. 2<. mat = RandomInteger@9. 87.50. 5<D. Null< Example: matrix manipulation In this example we will create functions to switch rows or columns of a matrix. In[23]:= MatrixForm@matD Out[24]//MatrixForm= 7 7 8 6 7 4 9 5 2 6 0 8 2 0 8 2 3 6 4 3 6 9 2 1 6 We could use a parallel assignment to switch two rows. 2016 .882004.tmpD In[21]:= TimingA DoAf2@100D. 9105 =E E Out[19]= 80. the need for localization becomes apparent quickly. Null< In[20]:= f2@n_D := With@8tmp = NüRange@nD<.

85. lmatD This can be written a bit more compactly using list component assignment on the correct r2_<D := Module@8lmat = mat<.006 Cambridge Books Online © Cambridge University Press. lmat@@r1DD<. r2<DD = lmat@@8r2. 3<D êê MatrixForm Out[31]//MatrixForm= 7 8 7 6 7 4 5 9 2 6 0 2 8 0 8 2 6 3 4 3 6 2 9 1 6 Using local variables in this situation is preferable as the original matrix is left unchanged. switchRows@mat.50.50 on Wed May 18 01:16:10 BST 2016.253.1017/CBO9780511972942. we return the value of lmat. 8r1_. Downloaded from Cambridge Books Online by IP 157. In[27]:= switchRows@mat_. 8lmat@@r1DD. r2_<D := Module@8lmat = mat<. lmat@@8r1. For example. lmat@@r2DD< = 8lmat@@r2DD. this switches the first and the last row.5. and only operating on that expression. 2016 . mat = RandomInteger@9. r1<DD. lmatD SeedRandom@123D. In[28]:= In[29]:= In[31]:= switchRows@mat_. lmat.5 Scoping constructs In[26]:= 151 mat êê MatrixForm Out[26]//MatrixForm= 7 8 7 6 7 4 5 9 2 6 0 2 8 0 8 2 6 3 4 3 6 2 9 1 6 We can avoid this problem by using a local variable. In[32]:= mat êê MatrixForm Out[32]//MatrixForm= 7 7 8 6 7 4 9 5 2 6 0 8 2 0 8 2 3 6 4 3 6 9 2 1 6 You can even use negative indices to count rows from the end. When the computation is done. 82. 8r1_. http://dx. 5<D. not the original matrix.doi.

8.6<D must be between 1 and 5.1. 1<. Out[36]= 887. 9. 2.Functional programming 152 In[33]:= switchRows@mat. 81. Hint: consider using the Accumulate function. The PerfectSearch function defined in Section 1. c2<D switchColumns@mat. 6<. 3. http://dx. 9<. 87. 6. 0<. 2.006 Cambridge Books Online © Cambridge University Press. The step directions can be taken to be the compass directions with north represented by 81. 8. 8c1. 0. Exercises 1. one that will fail if you are not careful with the row or column numbers. 86. 2016 .1017/CBO9780511972942. Write a compound function definition for the location of steps taken in an n-step random walk on a square lattice.1 is impractical for checking large numbers because it has to check all numbers from 1 through n. 88. 0. 6<< In Exercise 1 of Section 5.253. say. Modify PerfectSearch so that it accepts two num- Downloaded from Cambridge Books Online by IP 157. 4. 6<D switchRows::badargs : The absolute value of the row indices 1 and 6 in switchRows@mat. 0<. 6. it is inefficient to check all numbers from 1 to 1000 if you are only looking for perfect numbers in the range 500 to 1000.7 we will do some argument checking and issue an appropriate message when bad arguments are passed to these functions. 81. If you already know the perfect numbers below 500. 5. 87. c2_<D := TransposeüswitchRows@Transpose@matD. and so on. 2. In[34]:= In[35]:= switchColumns@mat_. 2<. south by 8. 83.81.50 on Wed May 18 01:16:10 BST 2016. -1<D êê MatrixForm Out[33]//MatrixForm= 7 7 8 6 7 6 9 5 2 4 8 8 2 0 0 3 3 6 4 2 6 9 2 1 6 Switching columns is basically switching rows of the transposed matrix and then transposing back.doi. the size of the matrix. 2. 4<D êê MatrixForm Out[35]//MatrixForm= 7 7 8 6 7 4 9 5 2 6 2 3 6 4 3 0 8 2 0 8 6 9 2 1 6 This is a fairly simplistic function. In[36]:= switchRows@mat. 4.50. 3.

e<D Out[2]= 9a2 . Often in processing files you are presented with expressions that need to be converted into a format that can be more easily manipulated inside Mathematica. 8a. and FunctionA8x. 5. day.doi.50 on Wed May 18 01:16:10 BST 2016.50. A number. such as Map.6 Pure functions Many computations that you perform involve creating and using a function quickly to perform some transformation on an expression.1VSFGVODUJPOT bers as input and finds all perfect numbers between the inputs. 15< 5. bodyE for a pure function with more than one variable. c. 5. seconds=. e2 = But what if you could use a function “on the fly” without creating an explicit definition? That is what you can do with pure functions. A pure function is a function that does not have a name and that can be used “on the spot”. PerfectSearchAa. http://dx. 4. bodyE for a pure function with a single variable x (any symbol can be used for the variable). Write a function convertToDate@nD to convert a number consisting of eight digits such as 20120515 into a list of the form 82012. Syntax of pure functions The basic form of a pure function is FunctionAx. month. bE will produce a list of all perfect numbers in the range from a to b. a positive integer k. Include rules to handle the cases of zeroing out one column or a list of nonconsecutive columns. The body looks like the right-hand side of a user- Downloaded from Cambridge Books Online by IP 157. c. hour. 2016 . Fold . at the moment it is created. b.1017/CBO9780511972942. 3. minutes. Typically.006 Cambridge Books Online © Cambridge University Press. Mathematica represents its dates as a list in the form 9 year. In[2]:= Out[2]= convertToDate@20 120 515D 82012.. and computes all k-perfect numbers in the range from a to b. For example. In[1]:= f@x_D := x2 In[2]:= Map@f. This is often convenient. 2012. y. Create a function zeroColumns@mat. c2 . m . Redefine PerfectSearch from the previous exercise so that it accepts as input two numbers a and b. b2 . 5. or Nest . nD that zeros out columns m through n in matrix mat. is k-perfect if the sum of its proper divisors equals k n.153 5. especially if the function is only going to be used once or if it will be used as an argument to a higher-order function. a file may contain dates in the form 20120515 to represent May 15. c2 . 15<. you introduce a formal function definition and then use that function explicitly. n. …<. For The built-in function Function is used to create pure functions.253. Use your rule to find the only three 4perfect numbers less than 2 200 000.

plot it. As an example. 8x.Functional programming 154 defined function definition. 2<E 4 3 2 Out[7]= 1 -2 -1 1 2 Downloaded from Cambridge Books Online by IP 157. where argument names would be. z2 E There is also a standard input form that can be used in writing a pure function which is easier to write than the Function notation but can be a bit cryptic to read.50. integrate it. …. the parentheses in the following example are purely for readability and can be omitted if you wish. In[4]:= Out[4]= FunctionAz. or. and so on are used. z2 E@6D 36 Here is the same thing.006 Cambridge Books Online © Cambridge University Press. In[6]:= Out[6]= In[7]:= Ò 2 &@10D 100 PlotAÒ 2 &@xD. The right-hand side of the function definition is rewritten by replacing the variable by the number sign. you can do anything with a pure function that you can do with a formally-defined function. 2016 . but using the more cryptic shorthand notation. In[5]:= Out[5]= IÒ 2 &M@6D 36 In fact. #2. #1.1017/CBO9780511972942. You can evaluate it at a value. In[3]:= FunctionAz.253. hash symbol (#) and ending the expression with the ampersand symbol (&) to indicate that this is a pure function. First we show the pure function using Function . z2 E Out[3]= FunctionAz. and so on. A pure function can be used exactly like more conventional looking functions. with the variables x.doi. y. Ò2 & If there is more than one variable.50 on Wed May 18 01:16:10 BST 2016. by following the function with the argument values enclosed in square brackets. -2. here is a pure function that squares its argument.

5. 39.7762<. lisE 85. In[13]:= data = 824. xE x3 Out[8]= 3 If you prefer.1331. Cambridge Books Online © Cambridge University Press. 21. 6. http://dx. This has the same effect as defining the function in the more traditional manner (although.1488.7434.6 Pure functions In[8]:= 155 IntegrateAÒ 2 &@xD.39001. In[14]:= ListPlot@dataD 40 30 Out[14]= 20 10 2 4 6 8 10 12 14 Downloaded from Cambridge Books Online by IP 157. 27.253. as we will see later. So that is what we need to map across this list.50. so. let us first look at a few basic examples of the use of pure functions. 26. 22.doi.1039. 2016 .1619. squared@6D 36 Pure functions are very commonly used with higher-order functions like Map and Apply . Here is a list of numbers.50 on Wed May 18 01:16:10 BST 2016.8856. -5. 25.669. 14. In[12]:= Out[12]= MapAÒ 2 + 1 &.321. 24. 20.7676.1<. The pure function that does this is Ò2 + 1 &.8705. before going further. Now suppose we wished to square each number and then add 1 to it. 9.1017/CBO9780511972942. 38.8177. 24.21< In the next example we will create a set of data and then use the Select function to filter out outliers. 29. 23. In[11]:= lis = 82.4736. working with pure functions can give significant speed increases on many types of computations). A plot of the data shows there are two outliers. In[9]:= In[10]:= Out[10]= squared = Ò 2 &. you can give a pure function a name and then use that name to call the function later.

9< Downloaded from Cambridge Books Online by IP 157.1017/CBO9780511972942. 7. EvenQ@Ò DDL &@82. 24. 25. 21. 9.006 Cambridge Books Online © Cambridge University Press.8705.39. 23. 6. 22. in this case excluding all data points that lie outside of the range 20 to 30. 29. 9< Union@Rest@FoldList@Max.8856. 6. 7. 9< Here it is written using pure functions.50. 9. 0. 7. 24. 9. 8<D False HApply@And. 5. 3. 20. 5.Functional programming 156 We introduced the Select function in Section 5. In[15]:= Out[15]= Select@data. 0. 8<D Out[17]= False Here it is written using pure functions.doi. 2016 . In[18]:= Out[18]= In[19]:= Out[19]= Function@lis. In[22]:= Out[22]= In[23]:= Out[23]= Function@x. Union@Rest@FoldList@Max. 6. 7. so we will convert some of the functions we defined earlier into pure functions. 2<D 82. 6. 4. EvenQ@lisDD In[17]:= listEvenQ@82.8177.4736. Recall Select@expr.669. 27. 7. Apply@And. 4. testD returns those elements from expr that return True when test is applied to them. 2<D 82. http://dx.1488. In[20]:= maxima@x_D := Union@Rest@FoldList@Max. 4. 7.2. xDDDD@ 0. We will use a pure function as the test. Ò DDD &@82.1619. 6.50 on Wed May 18 01:16:10 BST 2016. xDDD In[21]:= maxima@82.7762< Using pure functions A good way to become comfortable with pure functions is to see them in action. 8<D False maxima This function returns each element in the list greater than all previous elements. 3. 6. 5. showing both the shorthand notation and the Function form so that you can decide which you prefer to use. In[16]:= listEvenQ@lis_D := Apply@And. 3. EvenQ@lisDDD@82.1039. 22.1331. 20 § Ò § 30 &D 824. 2<D Out[21]= 82. listEvenQ This function tests whether all the elements of a list are even.253.

_List?HLength@Ò D > 2 &LD True Even though the head of 8a. c< is List . b.3D In[32]:= Out[32]= sumInts@100D 5050 Indexing with pure functions Oftentimes it is necessary to index parts of an expression by the position of each element. because of the precedence Mathematica gives to evaluating various quantities. In[29]:= Clear@sumIntsD In[30]:= sumInts@n_?HIntegerQ@Ò D && Positive@Ò D &LD := Total@Range@nDD In[31]:= sumInts@-1.1017/CBO9780511972942.3D Out[27]= In[28]:= Out[28]= 1 sumInts@-3D 0 Some argument checking.5. c< is greater than 2.50. In[25]:= Out[25]= MatchQ@8a. The following works fine if n is a positive integer. c<. we are testing if 8a. b. Downloaded from Cambridge Books Online by IP 157. it is necessary to enclose the entire including the &. using pure function predicates can rectify this.006 Cambridge Books Online © Cambridge University Press. 2016 . b. http://dx.3D Out[31]= sumInts@-1.253.4. In the first example. MapIndexed is designed for this purpose and it is often used with pure functions.doi. In[26]:= sumInts@n_D := Total@Range@nDD In[27]:= sumInts@1. Since it passes both of these conditions. c<. b. but is not well-defined otherwise. c< has head List and if the length of 8a. the condition below fails since the list has length less than 4. b. In[24]:= Out[24]= MatchQ@8a. MatchQ returns True . In Exercise 1 in Section 5. in parentheses. you were asked to create a function to sum the integers 1 through n.50 on Wed May 18 01:16:10 BST 2016.6 Pure functions 157 Pure predicate functions The following examples use a pure function as a predicate to check various criteria. _List?HLength@Ò D > 4 &LD False Note that when using a pure function as in ? test.

a<. c<. 8c. MapAFunction@y. 8d. c. Ò1< &. 9.50 on Wed May 18 01:16:10 BST 2016.Functional programming 158 Given an expression to index. y + the shorthand notation can be used for each of the pure functions but care needs to be taken to avoid confusion as to which # variable belongs to which pure function.253. 4. d. 82. 5. In[37]:= Out[37]= MapAÒ 2 &. that govern their behavior in various ways. f@b. 2. e<.4. 85<<< Using pure functions you can modify this quite a bit by operating on either the index or the subexpression. 81<D. 7<D 816. 81<<. we use List .doi. 8b. 84. 49< When dealing with nested pure functions. In[36]:= Out[36]= MapIndexed@8Firstü Ò2. the key is to keep the variables straight. we get pairs of the form 8ei . b.1017/CBO9780511972942. 85<D< If instead of a symbolic function f. http://dx. the following pure function is a list consisting of the first part of the index (strip away one set of braces) followed by the element in that position. f@c. 50< Example: searching for attributes and options As described in Section 2. x2 EE@83. 8e. where ei is the ith element in the expression. y + 1D. many built-in functions have a set of properties. 83<<. In[33]:= Out[34]= expr = 8a. In[38]:= Out[38]= In[39]:= Out[39]= FunctionAy. For example. Downloaded from Cambridge Books Online by IP 157. For example. the following pure function is mapped over the list to square each element. functions that have the Listable attribute automatically map or thread across lists of arguments. f@e.50. exprD 881. 83. 8i<<. attributes. i). or. Note the order in which the arguments are slotted into these two pure functions – the outer function gets the arguments first. 2. f@d. 84<<. 83. b<. 2016 . With MapIndexed . For example. MapAFunctionAx. 2. 84<D. 82<<. the default behavior of MapIndexed is to create pairs (ei . and then to pass them as arguments to a function given as the first argument to MapIndexed . MapIndexed@f. in which case different variable names can be used. d<. 85. #2 refers to the index and #1 to the element itself. 7<D 810. exprD 88a. 83<D. exprD 8f@a. x2 E.006 Cambridge Books Online © Cambridge University Press. 7<E 89. 82<D. e<< Nested pure functions You can also create nested pure functions. In[35]:= Out[35]= MapIndexed@List. 64< FunctionAx. This can be avoided by using Function .

doi. this selects all those System` symbols that have the Constant attribute. Downloaded from Cambridge Books Online by IP 157. In[44]:= RandomSample@names.5. PlotRangePadding< One minor point to note: the output of Names is a list of strings. NumericFunction. p>F 6 3 2 1 : . PrecedesSlantEqual. CylinderBox. SortBy. In[45]:= FullForm@%D Out[45]//FullForm= List@"SetterBoxOptions". In[42]:= Out[42]= MemberQ@Attributes@SinD. "Sin". Protected< p p p SinB: .1017/CBO9780511972942. Attributes can take either a symbol or a string as an argument so we do not need to worry about the distinction here (but we will need to worry about this when we do something similar for options). "NumberForm". FileDate. "HilbertMatrix". "DelimiterMatching".50 on Wed May 18 01:16:10 BST 2016. 2 3 . 1.253. . NotebookClose. DoubleLeftArrow. 10D Out[44]= 8ListCorrelate. http://dx.006 Cambridge Books Online © Cambridge University "VerticalTilde"D Fortunately. In[46]:= Out[46]= Attributes@"Sin"D 8Listable.6 Pure functions In[40]:= Out[40]= In[41]:= Out[41]= 159 Attributes@SinD 8Listable. In[43]:= names = Names@"System`*"D. 0> 2 In this section we will create a function that searches the entire built-in symbol list for functions with a given attribute or option. . 2016 . Ordering. Socket. For example. "VirtualGroupData". formE returns true if an element of list matches the pattern form. Protected< Hopefully it is clear how we should proceed. MemberQAlist. We want to select all those System` symbols that have a given attribute.50. "DumpGet". NumericFunction. ListableD True A list of all the built-in functions is given by the following. It is easy to check one function.

Khinchin. UnitTriangle. Xnor. In[52]:= Out[52]= Options@Symbol@"Integrate"DD 8Assumptions ß $Assumptions. E. ConstantD &D 8Catalan. MachinePrecision. GoldenRatio. DiracComb. Glaisher. Downloaded from Cambridge Books Online by IP 157.doi. the user does not need to evaluate Names@"System`"D prior to using it as we did above. CoprimeQ. note that Options . AssumptionsD False The tree structure shows that the option names occur down at level 2.50. LCM. E. PrincipalValue Ø False< The second issue is that options are given as a list of rules which is a more deeply nested expression structure than the list of attributes. Times. In[51]:= Out[51]= Options@"Integrate"D 8< We can work around this by converting strings to symbols. UnitBox. GCD.Functional programming 160 In[47]:= Out[47]= Select@names. Pi< FunctionsWithAttribute@OrderlessD 8ArithmeticGeometricMean. BitXor.50 on Wed May 18 01:16:10 BST 2016. MachinePrecision. EulerGamma. ChampernowneNumber. DiscreteDelta.1017/CBO9780511972942. Degree. Multinomial. BitOr. DiracDelta. Khinchin. Max. GoldenRatio. MemberQ@Attributes@Ò D. EulerGamma. Degree. In[53]:= Out[53]= MemberQ@Options@IntegrateD. HeavisideTheta. 2016 . KroneckerDelta. Pi< Let us turn this into a function that takes the attribute as an argument. unlike Attributes . Min. In[48]:= FunctionsWithAttribute@attrib_SymbolD := Select@Names@"System`*"D. BitAnd. Xor< Attempting to mimic this function for options instead of attributes requires several adjustments. MemberQ@Attributes@Ò D. Glaisher. does not take a string as an argument. GenerateConditions Ø Automatic. Plus. First. Equivalent. HeavisidePi. http://dx. Note. Majority.253. ChampernowneNumber. UnitStep. this function is “selfcontained”.006 Cambridge Books Online © Cambridge University Press. attribD &D In[49]:= FunctionsWithAttribute@ConstantD Out[49]= In[50]:= Out[50]= 8Catalan.

5. we can simply turn off the display of the warning messages by using Quiet . NMinimize.1017/CBO9780511972942. Options::opmix : Cannot mix streams and non-streams in 8Courier. FindMaximum. Here then is our function. In[55]:= Out[55]= MemberQ@Options@IntegrateD. NRoots< Downloaded from Cambridge Books Online by IP 157. NMinValue. FindMinValue. FindMinimum.006 Cambridge Books Online © Cambridge University Press.50 on Wed May 18 01:16:10 BST 2016. MemberQ@Options@Symbol@Ò DD. 82<. NArgMax.6 Pure functions In[54]:= 161 TreeForm@Options@IntegrateDD Out[54]//TreeForm= List RuleDelayed Assumptions Rule $Assumptions GenerateConditions Rule Automatic PrincipalValue False So we need to instruct MemberQ to search at that level by giving it a third argument. opt. 82<D True Finally. ToExpression can only interpret strings or boxes as Mathematica input. FindFit. In[57]:= FunctionsWithOption@opt_SymbolD := Quiet@Select@Names@"System`*"D. http://dx. 2016 .50. MemberQ@Options@Symbol@Ò FindArgMin.doi.253. 10. NonlinearModelFit. InterpolationOrder. à ToExpression::notstrbox : FEPrivate`FrontEndResourceString@GetFEKernelInitD is not a string or a box. NMaxValue. FindRoot. Assumptions.<. In[56]:= Select@Names@"System`*"D. 82<D &D. à Since the computation is correct. NMaximize. NArgMin. FindMaxValue. note that warning messages are issued for some of the symbols. NDSolve. 82<D &DD In[58]:= FunctionsWithOption@StepMonitorD Out[58]= 8FindArgMax.

tames. deforested. 6. . Create a function RepUnit@nD that generates integers of length n consisting entirely of ones. A naive approach to polynomial arithmetic would require three additions and six multiplications to carry out the arithmetic in the expression a x3 + b x2 + c x + d.Functional programming 162 Exercises 1.1017/CBO9780511972942. where there are now half as many multiplications. 7. 81. snorter. disadvantaged. 3.doi. huh. or 8. For example RepUnit@7D should produce 1111111. noised. In[4]:= Out[4]= In[5]:= Out[5]= MultiplyCountAa x3 + b x2 + c x + dE 6 MultiplyCount@d + x Hc + x Hb + a xLLD 3 In general. Write a pure function that moves a random walker from one location on a square lattice to one of the four adjoining locations with equal probability.50 on Wed May 18 01:16:10 BST 2016. silencer. Rewrite the code from Section 5. 0< with equal likelihood. Using Horner’s method for fast polynomial multiplication. RandomSample@words. 24D 8leafage.006 Cambridge Books Online © Cambridge University Press. monopolies. satanists.3 for finding the next prime after a given integer so that it uses pure functions instead of relying upon auxiliary definitions addOne and advisedly. interpolates. Here is the list of words in the dictionary that comes with Mathematica.1<.2. this expression can be represented as d + xHc + xHb + a xLL.253. 82500<D. Write a function to sum the squares of the elements of a numeric list. http://dx. uncorrupted. use this pure function with NestList to generate the list of step locations for an n-step random walk starting at 80. soapboxes. the number of multiplications in an n-degree polynomial is given by: In[6]:= Out[6]= Binomial@n + 1. 4.2 you were asked to create a function to compute the diameter of a set of points in n-dimensional space. Now. individuals. the function should return 80. You can see this using the MultiplyCount function developed in Exercise 8 of Section 4. inflicter. 0<. lithosphere. cocci. 2. In[1]:= data = RandomVariate@NormalDistribution@0. In Exercise 2 from Section 5.50. 1D.1. 0<. starting at 80. Find all words in the dictionary that start with the letter q and are of length five. Modify that solution by instead using the Norm function and pure functions to find the diameter. For example. 80. 2016 . archer. 2D 1 n H1 + nL 2 Downloaded from Cambridge Books Online by IP 157. 1<. squander. In[2]:= Out[3]= words = DictionaryLookup@D. 5. Moira. extract all those data points that are within one standard deviation of the mean of the data. tricking. Given a set of numerical data. throb. WWW< 8. 0<.

http://dx. and 5. For example.x1 + x2 L + a H.006 Cambridge Books Online © Cambridge University Press. You can check your result against the built-in ExponentialMovingAverage. 7<<< 10. 7. Downloaded from Cambridge Books Online by IP 157. In[10]:= Out[10]= ExponentialMovingAverage@8x1 . 85. aD 8x1 . xD d + x Hc + x Hb + a xLL Expand@%D d + c x + b x 2 + a x3 9. x1 + a H. x3 <. 4. 8<<. 4. In[7]:= Out[7]= In[8]:= Out[8]= Horner@8a. 6<<. 88. 7. 5<<. For example. x1 + a H. 83. c.253. Here is some sample output that your function should generate. d<. 86.50. 83. 4. whereas Horner’s method grows linearly. 82. vertex 2 is connected to vertices 1.a H. Use FoldList to compute an exponential moving average of a list 8x1 . Generate a sorted sequence of all Hamming numbers less than 1000.x1 . 82.x1 + x2 L. 8<<. 2016 .50 on Wed May 18 01:16:10 BST 2016. x2 . 8<<. of course. consider the graph gr below. A well-known programming exercise in many languages is to generate Hamming numbers. 4.x1 + x2 L + x3 L< 11. and so on. x2 . typically the adjacency structure takes the following form where this syntax indicates that vertex 1 is connected to vertices 2 and 8<<. Create an adjacency structure for any graph. directed or undirected.doi. Graphs that are not too dense are often represented using adjacency structures which consist of a list for each vertex vi that includes those other vertices that vi is connected to. In[9]:= gr = RandomGraph@88. 82. varE that gives a representation of a polynomial in Horner form. Create a function HornerAlis. 85. 5. b. 81. 3. These are numbers that divide powers of 60 (the choice of that number goes back to the Babylonians who used 60 as a number base). 7< The adjacency structure is then the list of adjacency lists for every vertex in that graph.5. 82.1017/CBO9780511972942. 83. sometimes referred to as regular numbers. 6. 81. 3. the adjacency list for vertex 8 in the above graph would be: 83. 5. 4. x3 <. The key observation is that these numbers have only 2. 5<<. 12<. 881.6 Pure functions 163 This. VertexLabels Ø "Name"D Out[9]= Start by creating an adjacency list for any given vertex. 84. It is common to prepend each adjacency list with its vertex. a list of those vertices to which the given vertex is connected. and 5 as prime factors. grows quadratically with n. 87. that is.

how will the user figure out the correct syntax. That how will they get helpful information. it is always a good idea to think about the user interface to your code. In this section we discuss how you can set up your functions so that they inherit this framework. or customers.0 But there is also a mechanism for overriding the default behavior by specifying optional arguments. or options. For example. 0. Downloaded from Cambridge Books Online by IP 157.50 on Wed May 18 01:16:10 BST 2016. In this section. we will show how to write options for your functions so that they behave like the built-in options in Mathematica. In[1]:= Plot@Sin@xD. 2016 .5 Out[1]= 1 2 3 4 5 6 -0.253. Another piece is using optional arguments. one used by the built-in functions in Mathematica. students. Options When writing your own programs. options. is to use optional arguments to specify some variant or special case rather than to have a separate function for each such case. The easier it is for a user (including yourself!) to actually use your code.Functional programming 164 5. A cleaner approach. generally you design the argument structure in such a way that it covers the most common cases for which you intended to use this function. it is often difficult to predict how a user will interact with them. write separate functions to handle special cases. One of the pieces of this framework is a mechanism for passing messages when a bad argument is given or a certain condition occurs.doi. When you create a function. but the problem with having a separate function for each special case is that the user can soon become overloaded with the variety of functions to learn. and so on. 8x. or simply.1017/CBO9780511972942. Options are specified following any required arguments and are generally given as a rule: optionname Ø value. to modify the default behavior of your functions.5 -1.006 Cambridge Books Online © Cambridge University Press.0 0. the more likely it is to be used for its intended purpose. given the required arguments. for example. You might. the Plot function returns a basic plot. One of the hallmarks of modern languages is that they provide a framework for you to apply standard design principles making it easier to develop programs that look and behave in a consistent manner.50. 2 p<D 1.7 Options and messages When developing programs that will be used by your colleagues. http://dx. making them behave just like built-in Mathematica functions in terms of argument structure and messaging.

the following indicates that a function named myFun will have two optional arguments. GridLines Ø Automatic. For example. myFun@x_. opt2 Ø b< The second piece of the options framework is to set up the argument structure to allow for optional arguments. the required argument is x and this statement indicates that some number (possibly zero) of optional arguments will follow that required argument.50 on Wed May 18 01:16:10 BST 2016.1017/CBO9780511972942. opt1 and opt2 and declares their default values to be a and b.doi.7 Options and messages In[2]:= 165 In[4]:= myFun@x_. opt1 Ø x. 2 p<. http://dx.50.5 -1. In[6]:= Out[6]= myFun@a. The first part of the framework is to declare that a function will have optional arguments and identify their names and default values. This is done by using OptionsPattern following any required arguments.253.006 Cambridge Books Online © Cambridge University Press.0 -0. 2016 .8 and then again repeatedly in later chapters.0 0. opt2 Ø b< 8opt1 Ø a. 0.5 Out[2]= 0. Frame Ø TrueD 1. first with default values for the options. respectively. OptionsPattern@DD := 2 x + 3 OptionValue@opt1D + 4 OptionValue@opt2D Let us try it out. In[5]:= Out[5]= myFun@aD 2a+3a+4b Now exercise the options. In[3]:= Out[3]= Options@myFunD = 8opt1 Ø a. 8x.5. opt2 Ø yD 2a+3x+4y Downloaded from Cambridge Books Online by IP 157. So in the example below.0 0 1 2 3 4 5 6 This provides a consistent framework for modifying the default behavior of the built-in functions. Below we will outline this framework and then start to put it into action at the end of this chapter in Section 5. OptionsPattern@DD := … The third piece of the framework is using OptionsValue to extract the value of a given option in the function definition.

There are many times when it would be useful to use. rather than using a separate Options@…D = … statement. all inherited from ListPlot . that is.doi.50. This way the user-passed options. you could also set up the inheritance of the options directly in the definition for your function. you just need to borrow it. FillingStyle Ø 88Purple. opts : OptionsPattern@DD := ListPlot@lis. appearing first.1017/CBO9780511972942. PlotLabel Ø Style@"A stem plot". Frame Ø True.50 on Wed May 18 01:16:10 BST 2016. Fortunately. points of height specified by the values of the data with lines drawn to the axis. In[10]:= StemPlot@Range@8D. StemPlot@lis_. this is quite straightforward using Options . Downloaded from Cambridge Books Online by IP 157. In[9]:= StemPlot@Range@12DD Out[9]= Here we exercise some of the Filling Ø 4.006 Cambridge Books Online © Cambridge University Press. This is done by having opts precede any other options we wish to use. some or all the options from a built-in function. "Menu"DD A stem plot 8 6 Out[10]= 4 2 0 0 2 4 6 8 As an alternative to how we set up the options for StemPlot. In[7]:= Options@StemPlotD = Options@ListPlotD. Dashed<<. http://dx. 2016 . will override any similarly named options that come later. opts. so good.Functional programming 166 So far.253. This saves time and effort in that the structure already is in place. We will create a function StemPlot that inherits options from ListPlot and displays discrete data as stems. or inherit. Filling Ø AxisD We named the optional arguments opts so that we can slot whatever options are given into ListPlot . but let us use the options framework to do something a bit more interesting.

1017/CBO9780511972942. opts. n > 1. opts : OptionsPattern@ListPlotDD := ListPlot@lis.". 4. Messages have names of the form symbol::tag.5 in the example on displaying DNA sequences and again in the visualization functions in Section 10. Messages When you give an invalid argument to a Mathematica function. Here is the original definition. In[12]:= Inverse@81. this function returns unevaluated for any argument that does not match the pattern n_Integer ê.7 Options and messages In[11]:= 167 StemPlot@lis_.5.006 Cambridge Books Online © Cambridge University Press.50.<D Inverse::matsq : Argument 81. In[15]:= CompositeQ::badarg = "Bad argument to CompositeQ. 2016 .5<D You can set up your own functions to do likewise.3.doi. In[14]:= CompositeQ@pD Out[14]= CompositeQ@pD We would like to set up a message that is issued whenever a bad argument is passed to CompositeQ. The tag should be chosen to reflect the purpose of the message. It should be an integer greater than 1. 4. Let us set up a message for the simple function CompositeQ discussed in Section 5. It is a good candidate for a warning message when it is given arguments that do not match this pattern. à Out[12]= Inverse@81. http://dx. It should be an integer greater than 1. The basic framework is: define the message and then use a rule to issue the message under the appropriate conditions. So in our case we will create a message CompositeQ::badarg.2. 2. Downloaded from Cambridge Books Online by IP 157.5< at position 1 is not a non-empty square matrix. we create a general rule that covers all arguments other than integers greater than 1 which is covered by the rule we wrote above. In[16]:= CompositeQ@n_D := Message@CompositeQ::badargD In[17]:= CompositeQ@pD CompositeQ::badarg : Bad argument to CompositeQ.2.4 we will look at some variations of this options framework in which you can mix options from different functions. it returns a warning message.3. 2. 2.50 on Wed May 18 01:16:10 BST 2016. n > 1D := Not@PrimeQ@nDD As written. In[13]:= CompositeQ@n_Integer ê. To issue this message. Filling Ø AxisD At the end of Section where symbol is the symbol with which you want to associate the message.

making the pattern match fail (which causes the input to be returned). Out[26]= CompositeQ@8a. c<D Downloaded from Cambridge Books Online by IP 157.Functional programming 168 So far.". also return the input unevaluated. http://dx. the If statement returns True . In[18]:= FactorInteger@pD FactorInteger::exact : Argument p in FactorInteger@pD is not an exact number. nD. in addition to issuing the warning.006 Cambridge Books Online © Cambridge University Press. In[20]:= CompositeQ@n_D := Message@CompositeQ::badarg. b. Message@CompositeQ::badarg. 2016 . the conditional is satisfied. If the argument is not an integer greater than 1.1017/CBO9780511972942. b. We could go a bit further and pass the bad argument itself into the message. FalseD := NotüPrimeQ@nD CompositeQ@pD CompositeQ::badarg : Argument p in CompositeQ@pD is not an integer greater than 1. Out[25]= In[26]:= CompositeQ@pD CompositeQ@8a.50 on Wed May 18 01:16:10 BST 2016. c< in CompositeQ@8a. c<D is not an integer greater than 1. Builtin functions do this automatically. so good. nD In[21]:= CompositeQ@pD CompositeQ::badarg : Argument p in CompositeQ@pD is not an integer greater than 1. and the right-hand side of the definition will be invoked. then the message is issued and False is returned to the condition. We can go one step further and create a more general rule. If@TrueQ@Head@nD ã Integer && n > 1D. In[22]:= Clear@CompositeQD In[23]:= CompositeQ@n_Integer ê. is an integer greater than 1. If it is. b. n. and so the right-hand side is not evaluated. n > 1D := Not@PrimeQ@nDD In[24]:= In[25]:= CompositeQ@n_D ê. True. b. In[19]:= CompositeQ::badarg = "Argument `1` in CompositeQ@`1`D is not an integer greater than 1.50. c<D CompositeQ::badarg : Argument 8a. The If statement below checks to see if the Then use a two-argument form of Message to issue the warning with a value slotted into the string. one that could cover more than one argument or more complicated argument structures and.doi. à Out[18]= FactorInteger@pD This is accomplished by using `1` to indicate the position in the string to slot in a value.

5. 8a. In[1]:= mat = RandomInteger@80.2<D must be between 1 and 4. 4<D. à Out[27]= In[28]:= 84.80. 2. 0<< 2. In[4]:= switchRows@mat. Out[3]= 883. b<.85. 5. 9<. 1. 0. Create a message for this function that is issued whenever a row index greater than the size of the matrix is used as an argument. you could have multiple messages associated with any symbol by writing another symbol::tag and modifying your code appropriately. 5. à Out[28]= Inverse@88a. 2016 .1017/CBO9780511972942. In Section 5.5 we developed a function switchRows that interchanged two rows in a matrix. b<<D Inverse::sing : Matrix 88a. Downloaded from Cambridge Books Online by IP 157. 7. 4<. 1<. 80. 4<. 2<D switchRows::badargs : The absolute value of the row indices 0 and 2 in switchRows@mat. 3. 84. 1. 85. 9. 2<D switchRows::badargs : The absolute value of the row indices 5 and 2 in switchRows@mat. This is what functions like Inverse do for the various arguments that could be given. so that an appropriate message is issued if the argument is not a list of numbers. b<< is singular. b.doi. 2. b. For example. the size of the matrix. 1<. b<<D Exercises 1.006 Cambridge Books Online © Cambridge University Press. Create an error message for StemPlot. MatrixForm@matD Out[2]//MatrixForm= 3 5 5 4 In[3]:= 5 9 0 2 1 7 7 3 8 4 1 0 switchRows@mat. 9. b<. 3. 85. the size of the matrix.50. Out[4]= 883.7 Options and messages 169 Of course. c<D Inverse::matsq : Argument 8a. 84. 7. developed in this section.253. c<D Inverse@88a. b. 7.50 on Wed May 18 01:16:10 BST 2016. 7. b<. 85. 8<. In[27]:= Inverse@8a. 8<. 85. 8a. 8a. 0.2<D must be between 1 and 4. http://dx. 0<< You should also trap for a row index of 0. c< at position 1 is not a non-empty square matrix. 85.

The examples include a problem from signal processing on computing Hamming distance. 0D. SameQ@x.50 on Wed May 18 01:16:10 BST 2016. FalseD 3 Downloaded from Cambridge Books Online by IP 157. SameQ@1. 0<<D 8False. yD will return True if x and y are identical. trying to minimize) that error. Various tests of equality are available. 80. 0. 0. the Hamming distance is defined as the number of nonmatching elements and so gives a measure of how well these two lists of binary digits match up.50.doi.Functional programming 170 5.0D True Here is what SameQ returns for the different pairings of binary numbers.006 Cambridge Books Online © Cambridge University Press. we will create a function to compute the Hamming distance of a binary signal. 0. In[1]:= Out[1]= In[2]:= Out[2]= SameQ@0. real-world problems. 1<. It differs from Equal (ã) in that. 0D. but SameQ is testing for identical structures. SameQ@1. A major concern in telecommunications is measuring (and of course. In[4]:= Out[4]= MapThread@SameQ. 2016 . For two lists of binary symbols. Others require localization constructs and auxiliary function definitions. 1. In[3]:= Out[3]= 8SameQ@0. False. False< and then count up the occurrences of False . and a data processing problem on cleaning/filtering arrays of data in which the notion of modular programs is discussed.8 Examples and applications In this section we will put several of the concepts we have explored to work in solving concrete. the Josephus problem. for Equal tests for numerical equality within a certain tolerance. Hamming distance When a signal is transmitted over a channel in the presence of noise.0D False Equal@0. 1. False. 1D< 8True. a practical problem involving the creation of a palette to open files from a project directory. 881. 0. True. 0.1017/CBO9780511972942. True. Let us first think about how we might determine if two binary numbers are identical. In[5]:= Out[5]= Count@%. errors often occur. Some of these solutions are short and avoid the use of auxiliary function definitions – so-called one-liners. In this first example.253. True< So we need to thread SameQ over the two lists of binary numbers. 1. one from ancient history. a graphical problem on the creation and display of regular polygons. http://dx.

There are numerous other approaches that you might consider – the Downloaded from Cambridge Books Online by IP 157. sig2DD 80. So if x and y can only be among the binary integers 0 or 1. 0. 1<. We will leave a discussion of the causes of this difference until Chapter 12. in this case two lists consisting of one million 0s and 1s.50. In[9]:= Out[9]= Total@%D 3 Here then is our bit-operator based version for the Hamming distance computation. 0. http://dx. FalseD BitXor@x. 0. 80. we will use some of the logical binary operators built into Mathematica. sig2DD Out[14]= In[15]:= Out[15]= 80. 1. 0. In[10]:= HammingDistance2@lis1_. lis2_D := Total@BitXor@lis1.5. 1. In[13]:= sig2 = RandomIntegerA1.253. 0. lis2DD In[11]:= HammingDistance2@81.497098. 0. 1. In[14]:= Timing@HammingDistance1@sig1. 0. 1<. 2016 .007763. yD returns the bitwise XOR of x and y. 499 922< Timing@HammingDistance2@sig1. 0<D 81. 1< And here are the number of 1s that occur in that list. In[12]:= sig1 = RandomIntegerA1. 1. 0<D 3 We might also try to solve this problem by a more direct approach. 1. 9106 =E. 1<.50 on Wed May 18 01:16:10 BST 2016. 1. 80. 0. BitXor will return 0 whenever they are the same and will return 1 whenever they are different. lis2_D := Count@MapThread@SameQ. 80.006 Cambridge Books Online © Cambridge University Press. In[8]:= Out[8]= BitXor@81. we have our first definition for Hamming distance. 0. Since we are dealing with binary information. 499 922< That is quite a difference in the efficiency of these two approaches! Using bit operators gives a speedup of almost two orders of magnitude.1017/CBO9780511972942. 1. 8lis1. 9106 =E.8 Examples and applications 171 Putting these last two pieces together. 1.doi. 1. 1. Note that BitXor is listable and so automatically threads over lists. 0<D Out[11]= 3 Let us compare the running times of these implementations using a large data set. 0. lis2<D. In[6]:= In[7]:= Out[7]= HammingDistance1@lis1_. 0.

We will restate the problem as follows: n people are lined up. Range@nD. d<DD 8c. We will create the list of n elements using Range@nD. 2016 . and so on until only one person remains in the line.006 Cambridge Books Online © Cambridge University Press. performed over and over again. We will start by changing the problem a bit (the importance of rewording a problem can hardly be overstated. the above computations are not a bad check on the built-in random number generator – we would expect that about one-half of the paired-up lists would contain different elements. c.253.doi. this problem has a definite mathematical interpretation that lends itself well to a functional style of programming. the key to most problem-solving resides in turning something we cannot work with into something we can). a< At this point it should be fairly clear where this computation is headed. iterate the pure function Rest@RotateLeft@ÒDD & until only one element remains.1D Downloaded from Cambridge Books Online by IP 157.1 iterations. http://dx. the group chose to commit suicide one by one. Here then is the function survivor. Legend has it though. A list of n elements will need n . In[16]:= Out[16]= Rest@RotateLeft@8a.50 on Wed May 18 01:16:10 BST 2016. that they decided to go around their circle of ten individuals and eliminate every other person until only one was left. The Josephus problem Flavius Josephus (37 – ca. see Herstein and Kaplansky (1978) or Graham. We want to take a list It can be encoded with the RotateLeft function (move the person at the front of the line to the back of the line) followed by the use of the Rest function (remove the next person from the line). Through his writings comes the following story. Rather than die at the hands of their enemy. 100 AD) was a Jewish historian who fought in the Roman–Jewish war of the first century ad. The statement of the problem indicates that there is a repetitive action. the third person is moved to the end of the line. d. In[17]:= survivor@n_D := Nest@Rest@RotateLeft@Ò DD &. The Josephus problem is stated simply: who was the last to survive? Although a bit macabre. n . b. the second person is removed from the line. and Patashnik (1994): The Romans had chased a group of ten Jews into a cave and were about to attack. Knuth. the first person is moved to the end of the line.Functional programming 172 exercises ask you to write implementations of HammingDistance that use Select and Cases and also one using modular arithmetic. using the Nest function.1017/CBO9780511972942. As an aside.50.

5. 1< RotateLeft 81. 1. 6. 5. RotateLeftD RotateLeft 82. n . Downloaded from Cambridge Books Online by IP 157. 4. 6. 6<. of course. we see that the survivor is the fifth starting position. 85<< Regular graphs/polygons Section 1. In[19]:= TracePrint@survivor@6D.8 Examples and applications 173 Trying out the survivor function on a list of ten. 1<. 5<. 85. In[18]:= Out[18]= survivor@10D 85< Tracing the applications of RotateLeft in this example gives a clear picture of what is happening. 5. 1. The advantage of this approach is that we can then take advantage of the style and formatting functionality built into Graph objects. 81. 3. 1<. 6. 5< Out[19]= 85< And.1 included some brief code to create and display regular polygons from points equally spaced on a circle.253.50. 3< RotateLeft 86. 6. 2. In[20]:= Out[20]= With@8n = 6<. 2016 . 3. 1< RotateLeft 84. 3. 85. Using TracePrint with a second argument shows only the results of the applications of RotateLeft that occur during evaluation of the expression survivor@6D. Here we will use some of the built-in graph machinery together with several functional programming constructs to create an alternative implementation. 5< RotateLeft 83.1DD 881.50 on Wed May 18 01:16:10 BST 2016. 5. 3<.1017/CBO9780511972942. http://dx.006 Cambridge Books Online © Cambridge University Press. NestList@Rest@RotateLeft@Ò DD &. Range@nD.doi. 3.5. 83. 4. you could generate the list of survivors at each round by using NestList instead of Nest . 5. 1.

doi. 81<D 81  2. 82.002. In[24]:= Graph@%D Out[24]= Finally.1017/CBO9780511972942. In[22]:= Out[22]= pairs = Partition@Range@5D. Partition@Range@nD. adding several Graph options to stylize the graph. 2. we turn the rules into a graph object that will display as a polygon. 4  5.253. pairs. 83. The last argument to Partition indicates that the list is cyclic. 3. Note the need to apply UndirectedEdge at level 1.1 identified the vertices spatially as coordinates in the plane. http://dx.006 Cambridge Books Online © Cambridge University Press. 2<. 1<< We next turn each pair of vertices into an (undirected) edge.50. VertexSize Ø 0. Whereas the code in Section 1. 81<D. 5< We need to connect vertex 1 to vertex 2. vertex 2 to vertex 3. 1D. 5. 1D 881. 2. 1. 3.Functional programming 174 Let us start by creating a regular pentagon. 2  3. In[25]:= RegularGraph@n_IntegerD := Graph@ Apply@UndirectedEdge. 5<.org/10. 84. and so on. graphs identify the vertices by their index. 3<. 85. In[23]:= Out[23]= Apply@UndirectedEdge. 4<. In[21]:= Out[21]= Range@5D 81. 2016 . 2. This is done by partitioning this list of five vertices into overlapping pairs. EdgeStyle Ø ThickD Downloaded from Cambridge Books Online by IP 157. a graph with five vertices labels them 1. 3  4. 5  1< Then. 2. 4. 4. 1. we put all the above pieces together to create a reusable function.50 on Wed May 18 01:16:10 BST 2016.

50 on Wed May 18 01:16:10 BST 2016.5. 2  3.doi. http://dx. 4. 2.006 Cambridge Books Online © Cambridge University Press. BaselinePosition Ø Automatic.50. 1<< Then we thread UndirectedEdge over these paired vertices. AxesOrigin Ø Automatic. 5  1< Using the options framework introduced in Section 5.1017/CBO9780511972942. In[30]:= Options@RegularGraphD = Options@GraphD.253. 3. we have hard-coded the two options. 2016 . VertexSize and EdgeStyle. In[31]:= RandomSample@Options@RegularGraphD. 5. 3. 4  5. RotateLeft@lisD< 881. using MapThread. In[29]:= MapThread@UndirectedEdge. EdgeStyle Ø Automatic< Downloaded from Cambridge Books Online by IP 157. In[27]:= Out[28]= lis = Range@5D. 8D Out[31]= 8AspectRatio Ø Automatic. 3  4. 82. FrameTicksStyle Ø 8<. That is fine for the default representation. GraphLayout Ø Automatic. VertexLabels Ø Automatic. First. Properties Ø 8<.7.8 Examples and applications In[26]:= 175 RegularGraph@5D Out[26]= In the above implementation. pairs = 8lis. pairsD Out[29]= 81  2. Let us also try a different approach to constructing the vertex rules. set up RegularGraph to inherit all the options of Graph . but let us take advantage of all the rich formatting and stylistic functionality built into Graph objects. we rotate the original list one position to the left. 5<. This is done by passing the options for Graph to our RegularGraph function.

using a variety of options to stylize the output.253. 8DD Out[33]= Representing these objects as graphs provides not only styling and labeling options.006 Cambridge Books Online © Cambridge University Press. 8verts.1017/CBO9780511972942. Graph@ MapThread@UndirectedEdge. VertexSize Ø Small. but also gives access to functions for operating on and measuring graphs. 2< Or you can determine if another graph is isomorphic to a regular graph. verts.doi. displayed as a graph. is really a constant. VertexStyle Ø Red. 2. EdgeStyle Ø ThickDD Here then is a regular pentagon. an expression that does not change in the body of the function. Downloaded from Cambridge Books Online by IP 157. In[33]:= RegularGraph@5. opts. 2016 . meaning that every vertex has two edges. In[32]:= RegularGraph@n_Integer. opts : OptionsPattern@DD := With@8verts = Range@nD<. 2. 2.Functional programming 176 We use the localization construct With here as the list of vertices. HypercubeGraph@2DD True As an aside. VertexLabelStyle Ø Directive@"Menu". VertexSize Ø on Wed May 18 01:16:10 BST 2016. http://dx. In[34]:= Out[34]= VertexDegree@RegularGraph@5DD 82.50. For example. a quick check shows that regular graphs are 2-regular. the built-in CycleGraph@nD returns a similar object. RotateLeft@vertsD<D.002. In[35]:= Out[35]= IsomorphicGraphQ@RegularGraph@4D. VertexLabels Ø "Name".

4. R05F9.5<.7. and essentially all processes in living cells.006 Cambridge Books Online © Cambridge University Press.7. This imports that file from the internet and displays the first twelve entries. F29G6. 81<D Downloaded from Cambridge Books Online by IP 157. 8B0024. a process in which proteins control the signaling into and out of the cell.50 on Wed May 18 01:16:10 BST 2016. 8B0001. 8B0024. In this section.1<. "TSV"D. protein2 < indicating an interaction between these two named proteins. B0228. a heavily studied organism (Worm Interactome Database).7. We will work with proteins from the worm Caenorhabditis elegans. F19B6.253.<D := Apply@DirectedEdge.1<. The data. is key to the study of diseases including many cancers. F37H8.1<. where each edge represents an interaction between two proteins (vertices).txt".14.1<< The data are of the form 8 protein1 . and graph tools to visualize proteins within networks that have a high level of interaction.3. pattern matching.dfci. C06A1. signal transduction. Using the function ToGraph. 8B0001.1<.14. In[39]:= ToGraph@lis : 88_. 8B0024.1<.3<.10<.50.5. are in the form of a text file. signal transduction. courtesy of Dana-Farber Cancer Institute and Harvard Medical School. 8B0001. 12D Out[38]= 88ÒIDA. Y69H2. Y40B10A. In[38]:= Take@data. lis. 2016 . C05G6. 8B0024.10. 8AC3. C06E2.3<. 8AC3.12. movement of molecules into and between cells.8 Examples and applications In[36]:= 177 CycleGraph@5.1017/CBO9780511972942. developed in Exercise 4 of Section 5.eduêC_elegansêgraphsê sequence_edgesêwi2007. B0281. 8AC3.. we turn these lists into edges.3. IDB<.2<. In fact. _< . 8AC3. Their importance in all cellular activity has given rise to active work in the visualization of these protein-protein interactions (PPIs). VertexLabels Ø "Name"D Out[36]= Protein interaction networks Proteins interact with other proteins in biological processes as varied as DNA replication.3. In[37]:= data = Import@ "http:êêinteractome.doi. we will combine some of the functional constructs.

proteins that have at least 12 interactions with other proteins.3  Y69H2. lisD In[41]:= ToGraph@Take@data.10".3  F29G6.7"D VertexDegree@ gr.14  B0228. " B0001. that is.3".2.1< We need to delete the first entry ("ÒIDA"  "IDB") which is meant as a comment.3". http://dx.1. as a result.50. Many of the interactions involve only two proteins as seen in the small components on the right and bottom of the above output.7  B0281. "Y69H2. AC3. 12DD Out[41]= 8ÒIDA  IDB. "R05F9. it is a bit difficult to discern detail. B0024.10.3".1.10"D 86 Downloaded from Cambridge Books Online by IP 157.3.doi.1.1. AC3. 5D êê FullForm Out[45]//FullForm= List@"AC3. We will take n = 12.7  F37H8. "F29G6. So in our protein network. In[46]:= Out[46]= VertexDegree@gr. _<D := Apply@DirectedEdge. and. 2016 . AC3.3  R05F9. Take@vertices.7  Y40B10A.Functional programming 178 In[40]:= ToGraph@lis : 8_. The vertices (the proteins) are strings. In[42]:= edgerules = ToGraph@Rest@dataDD. vertexD gives the number of edges incident to vertex in graph gr. B0001.006 Cambridge Books Online © Cambridge University Press. B0024. B0001. So we use ToGraph on Rest@dataD and then visualize the result with Graph . AC3. B0024.3.4  F19B6.10  C06A1.253. gr = Graph@edgerulesD Out[43]= It is a fairly dense graph showing all the protein interactions.1. B0024. In[44]:= vertices = VertexList@grD.14  C05G6.1017/CBO9780511972942.5. Our task in this example is to find the subgraph consisting of all those proteins with at least n interactions with other proteins.50 on Wed May 18 01:16:10 BST 2016. the vertex degree for vertex vi gives the number of interactions between that protein represented by vi and all other proteins. "AC3.12  C06E2.

W09C2.1.5. Ò D > 12 &LD 8R05F9. 89.4. 2016 . 1<. Y69H2. vertices with one edge occur 933 times in this network. 844. http://dx.2. 82. 64<. 839.doi. 107<.5. ZK858. C06G1. 845. 88. ZK121. W09C2. ZK1053. T11B7.9. 2. So from the tally below. There is only one vertex with 86 edges. 2<.5.4.3. we thread the inequality over the list of vertex degrees and pick those vertices for which this inequality is true. 933<. 6<. 2<. 2. 1<.9. DH11. C18G1. 816. 87. ZK1055. 6<. 3. 85. use Select with the appropriate predicate. Y69H2. F32B4. 21<.4. 849.4. 811. W10C8. 812. W05H7. 813.1017/CBO9780511972942. R02F2. 4< > 3 Out[50]= 81. 1<. K09B11. False. F44G3. ZK121. Y55F3C. 821. C18G1. Y65B4BR.< Thread is needed here because Greater (>) is not listable. 819.2.4. 818. C50F4.2. Y40B10A. 3. 2<. True< Downloaded from Cambridge Books Online by IP 157.4. K12C11. T21G5. 4< > 3D 8False.3. C06A5. 1<. 11<.1. K09B11. DH11.2.50 on Wed May 18 01:16:10 BST 2016. ZK849. F52E1.5. C36C9. ZK1053. 810. C36C9. F44G3.7.5. 847. 3<. ZK849. M04G12.2. 1<. C50F4. 86. R02F2.8 Examples and applications 179 A slightly different syntax for VertexDegree gives the degree for every vertex in the graph. and so on. 1<.006 Cambridge Books Online © Cambridge University Press. In[50]:= W10C8.6< Or. 2<. 19<. Y54E2A. ZK1055.10.253.2. 84. Y40B10A.5. T21G5. In[49]:= Out[49]= proteins = Pick@VertexList@grD. Y65B4BR. F52E1. 815. 1<< To extract all those vertices that have a vertex degree greater than 12.1.7. 830. F46A9.9. 4< > 3 In[51]:= Out[51]= Attributes@GreaterD 8Protected< Note that Thread can thread over two expressions that are not the same structurally. In[48]:= Out[48]= Select@VertexList@grD.5. 1<.7. Y54E2A.9. F01G10. 246<. HVertexDegree@gr. Y55F3C.1. 1<. 828. F46A9.3. F32B4.2.2. as in our example here.9. 3<.1. In[52]:= Out[52]= Thread@81. 2<.1. 3.4. 824. M04G12. 2. In[47]:= Out[47]= SortBy@TallyüVertexDegree@grD. K12C11.2. 814. T11B7.5. FirstD 881.1. 10<.10. False. C06G1. ZK858. 817. 1<. 3<. 2<. 83. C06A5. 2<.4.4. 886. 40<. W05H7. F01G10. 831. Thread@VertexDegree@grD > 12DD 8R05F9. vertices with two edges occur 246 times. 823.4.2.5.

p2D.006 Cambridge Books Online © Cambridge University Press. VertexStyle Ø Red.1  Y54E2A. Take@edges. We will use the notebook files ("*.5 C06G1. C36C9. C06G1.5  W05H7.4.9  F44G3. In[57]:= Graph@gr1. InfinityD. 12D 8C06A5. C36C9.9. C06G1. EdgeShapeFunction Ø "CarvedArrow"D Out[57]= The exercises include an extension of this PPI visualization in which you are asked to color the vertices according to that protein’s biological processes.1. This is particularly useful if you are working on a project consisting of numerous files. 2016 .2.5  F32B4.50 on Wed May 18 01:16:10 BST 2016.4. VertexSize Ø Large.4.9. C06G1.9.4.50. x_  x_D. all of which live in the same location. GraphLayout Ø "CircularEmbedding". C06G1.1  K09B11.1  K09B11.5  ZK121. VertexLabels Ø "Name".9.5  Y54E2A.5  ZK849. Hp1_  p2_L ê.3. VertexStyle Ø Directive@OrangeD. C06G1.9  DH11.3< We delete self-loops (although proteins certainly can interact with themselves).5  ZK849. C06A5.9. C06G1. Let us start by getting a list of files from a project directory. C06G1.9  C36C9. http://dx. C06G1.1  Y54E2A.5  K09B11. we use Graph and several options to visualize this PPI.2.doi. C36C9.5  K09B11.4.9. MemberQ@proteins. In[55]:= Out[56]= gr1 = DeleteCases@edges. C06A5.nb") from the directory PwM. C06G1.9  DH11. You could choose any directory containing your project Downloaded from Cambridge Books Online by IP 157.2.4. C06A5.9  F44G3. Take@gr1.3< Finally. 12D 8C06A5.3.5  ZK121. C06G1.4. p1D && MemberQ@proteins. In[53]:= In[54]:= Out[54]= edges = Cases@EdgeList@grD.5  Y54E2A. Palettes for project files In this next example we will use the functional constructs developed in this chapter to create a palette of hyperlinks to files in a given directory.4. C06G1. C36C9. C06A5. C06G1.5  F32B4.253.5  W05H7.Functional programming 180 Now we get all those interactions that involve proteins as defined above.1017/CBO9780511972942.2.5  DH11.1.9  C36C9. C06G1.

02Language. files<DDD. We wrap the list of links in Column to give a vertical list of buttons. the second argument is the target file for that label. The palette will consist of a column of buttons. 09Strings = Although it is not obvious in print.1017/CBO9780511972942.nb. In this case we will only work with the first nine files in this directory.006 Cambridge Books Online © Cambridge University Press. Clicking any of these links will open the corresponding file. we will use the basic file name. êLibraryêMathematicaêApplicationsêPwMê04PatternsAndRules. êLibraryêMathematicaêApplicationsêPwMê07Recursion. 06Procedural. files = Take@FileNames@"*. êLibraryêMathematicaêApplicationsêPwMê as given by FileBaseName . In[62]:= Out[62]= MapThread@Hyperlink@Ò1. 08Numerics. we thread Hyperlink over the labels and files. Downloaded from Cambridge Books Online by IP 157. Ò2D &. files<D 901Introduction. 8labels. Hyperlink@label. filesD 801Introduction. Note the use of a pure function to slot in each label and file in the correct location. "Applications".50 on Wed May 18 01:16:10 BST 2016. 03Lists.doi. êLibraryêMathematicaêApplicationsêPwMê05Functions. 06Procedural.nb. 07Recursion.nb". 04PatternsAndRules. 05Functions. As a label for each button.nb< Hyperlink has a two-argument form: the first argument is the label.253. êLibraryêMathematicaêApplicationsêPwMê02Language. one for each file.nb. In[61]:= Out[61]= labels = Map@FileBaseName.nb. 07Recursion.5. "PwM"<D. In[60]:= ? Hyperlink Hyperlink@uriD represents a hyperlink that jumps to the specified URI when clicked.nb.nb. dirD. In[63]:= CreatePalette@ Column@MapThread@Hyperlink@Ò1. the above list consists of hyperlinks to each of the files. In[58]:= Out[59]= dir = FileNameJoin@8$BaseDirectory. Ò2D &.8 Examples and applications 181 notebooks.nb. 04PatternsAndRules. à So we will need to create a list of labels corresponding to our list of files. http://dx. êLibraryêMathematicaêApplicationsêPwMê06Procedural. 02Language. êLibraryêMathematicaêApplicationsêPwMê03Lists. 03Lists. êLibraryêMathematicaêApplicationsêPwMê09Strings. uriD represents a hyperlink to be displayed as label. 9D 8êLibraryêMathematicaêApplicationsêPwMê01Introduction. 08Numerics. 05Functions. 8labels.nb. 09Strings< Now.50. Now let us create a palette of these links. 2016 .

we can add some styles to the links as well as options to Hyperlink. linkOpts = 8ImageSize Ø 8Automatic. Ò2.006 Cambridge Books Online © Cambridge University Press. many of the examples we have worked through resulted in short programs. FontColor Ø White<. linkStylesD.1017/CBO9780511972942. colOpts = 8Background Ø DarkerüGray. One of the advantages of such an approach is that everything you might need to run the program is contained in the body of your function. 16<<. palOpts = 8WindowTitle Ø "File Palette". Column. 2016 . With a little more work. 8labels. files<D. CreatePalette@Column@ MapThread@Hyperlink@Style@Ò1.doi. self-contained programs. http://dx. and CreatePalette.50 on Wed May 18 01:16:10 BST 2016. linkOptsD &.Functional programming 182 Here is a screenshot of this palette. Dividers Ø All<.253. colOptsD. palOptsD.50. Although it may seem convenient to put all auxiliary defini- Downloaded from Cambridge Books Online by IP 157. either what are often called “one-liners” or simply short. WindowElements Ø "MagnificationPopUp"<. Operating on arrays Up to this point. In[64]:= In[68]:= linkStyles = 8FontSize Ø

extract and work on the first column and then later extend this to all the other columns. http://dx.5. using a matrix-processing example: replacing “bad” entries in a matrix with the column mean. In[69]:= mat = 44 "NAN" 19 99 72 6 "NAN" 46 28 75 10 40 2 98 "NAN" 47 .org/10. First. Another issue has to do with efficiency. Several approaches using different patterns could be used. In working with tabular data collected by an instrument or by some other means. with the appropriate pattern. One large chunk of code with many definitions embedded is often difficult to debug.8 Examples and applications 183 tions into the body of a function. that is. The same holds for a program that returns an incorrect result. we will use a small matrix of integers. If your program takes longer than you think it should to run.006 Cambridge Books Online © Cambridge University Press. you occasionally find nonnumeric values (strings.” If an analysis of the matrix depends upon numeric values.doi.50. how do you locate the bottleneck? Modern programming design uses a modular concept to break up computational or programmatic tasks into small separate chunks and then put the pieces together in one program in such a way that you can isolate each part and diagnose errors or inefficient code more readily. for example) in the matrix where either the instrument has failed to collect a datum point for some reason or the value is “out of range. Cases .253. 2016 . To prototype. 1DD. In[70]:= col1 = mat@@All.50 on Wed May 18 01:16:10 BST 2016.1017/CBO9780511972942. MatrixForm@col1D Out[71]//MatrixForm= 44 NAN 19 99 We need to extract just the numeric values. Running the program may fail with several warning or error messages displayed and no clear indication at which line in your program the problem lies. compute the column mean using only the numeric values. there are several good reasons not to do so. in this section we will explicitly look at how a modular approach is implemented in Mathematica. Although we have been trying to adhere to this approach implicitly up to this point. take the column in which the nonnumeric value occurs. Downloaded from Cambridge Books Online by IP 157. will do that. and then replace the nonnumeric value with this mean. what should be used to replace the nonnumeric values? One solution is to replace them with the column mean. making it easier to check our work along the way.

50 on Wed May 18 01:16:10 BST 2016. 28. the above array is a list of the column vectors. 54. 75. 99< Cases@col1. Except@_StringDD 844. In[75]:= col1 ê. 47>> 3 Since we operated on the columns. :6. http://dx. 99< Then compute the mean of these numeric values. In[78]:= MatrixForm@Transpose@%DD Out[78]//MatrixForm= 44 72 6 124 3 54 46 28 75 19 10 40 2 99 98 74 3 47 Finally. _ ?NumberQD 844. In[76]:= colMean@col_D := col ê. 98<. 19. : 124 . Transpose@matDDD Downloaded from Cambridge Books Online by IP 157. 2016 . Transpose@matDD Out[77]= :844.50.1017/CBO9780511972942. We need to transpose back. _ ?NumberQDD 54 Replace the string "NAN" with the mean.253.006 Cambridge Books Online © Cambridge University Press. 99<. 74 3 >. "NAN" Ø Mean@Cases@col1.Functional programming 184 In[72]:= Out[72]= In[73]:= Out[73]= Cases@col1. let us put these pieces together: In[79]:= ReplaceElement@mat_D := Transpose@Map@colMean. 19. 2. 40. 872. 10. _ ?NumberQDD In[77]:= Map@colMean.doi. 46. "NAN" ß Mean@Cases@col. _ ?NumberQDD êê MatrixForm Out[75]//MatrixForm= 44 54 19 99 This operation needs to be performed on each column so we write a function that will be mapped across the columns of a matrix. In[74]:= Out[74]= Mean@Cases@col1.

and then create a second rule for ReplaceElement with a second argument to specify the string. 0.0851 -0.737 "NAN" -0.5038 -0.8809 .5081 0. str ß Mean@Cases@col. strD &.250175 -0.4013 With just a few small adjustments. not just "NAN" as above.0839 0.0839 0.8139 "NAN" -0.8139 -0. manual check on the second column.49 0.9343 0.3382 -0.9728 0. str_StringD := col ê.9473 0.doi. we introduce a second argument str and use that wherever "NAN" appeared in the previous version.5538 0.8139.5038 - Perform a quick.8 Examples and applications In[80]:= 185 ReplaceElement@matD êê MatrixForm Out[80]//MatrixForm= 44 72 6 124 3 54 46 28 75 19 10 40 2 99 98 74 3 47 and try it out on a larger matrix of approximate numbers. ReplaceElement can work with arbitrary strings. Rather than rewrite the entire program. Let us try out the new code.7658 -0.737 0.4061 0.6257 -0.9473 0. In[83]:= Out[83]= Mean@8-0. 2016 .5793 0.5081 0. Downloaded from Cambridge Books Online by IP 157. _ ?NumberQDD In[85]:= ReplaceElement@mat_. 0. 0.2648 -0.5882 0. writing a new rule to accommodate an arbitrary string. strD &.8809 -0.6257 -0.545925 -0.8783 In[81]:= mat = In[82]:= ReplaceElement@matD êê MatrixForm Out[82]//MatrixForm= 0.5538 0.006 Cambridge Books Online © Cambridge University Press.2648 -0.3668 0.3382 -0.1017/CBO9780511972942.50.50 on Wed May 18 01:16:10 BST 2016.4013 -0. In[84]:= colMean@col_.1984 -0. Transpose@matDDD Here you can see the real advantage of using modular code. http://dx.5793 0.9728 0.4061 "NAN" -0. we make one change to colMean.49 0. str_StringD := Transpose@Map@colMean@Ò .0851 -0.5882 0. and replacing colMean with the pure function colMean@Ò.1984 -0.3668 0. 0.3382.9343 0.6257<D 0.5038.7658 0. Instead of the “hard-coded” string "NAN" in columnMean.

0589 -0.4035 -0. 0. rmat = ReplacePart@mat. and finally runs ReplaceElement.5286.4242. RandomInteger@81. -0. 0.4444 0. Null< That is not too bad – processing a 1000ä1000 matrix in under a second.doi.3319.2591 -0.<.D< 880.253. Null<. -0.4444.4938 In[88]:= 0.5332<.6052 0.4287.2575.6955 0.4287 -0.877081.6499 0. 0. This creates a random matrix.4035. 8"NêA".6499 0. 8-0.5332 NêA -0.5286 0.9319<.6978 0. -0.2591.140302. 0.9319 0.099 0. Null<< In the exercises you are asked to go a bit further and rewrite ReplaceElement to accept an arbitrary list of strings that should be used as the nonnumeric values to be replaced with the column means.1017/CBO9780511972942. -0.8287 0. 0. 1000<D. 2016 . 8Timing@Inverse@matD.4293 -0. 0.6052.50.Functional programming 186 In[86]:= mat2 = 88-0. 8size.3319 0. 0. -0. That is on the same order of magnitude as some of the highly optimized built-in linear algebra functions. 8size.4242 0.5924<<. "NAN"D. In[89]:= Out[90]= With@8size = 1000<.4035 -0.0589.8287 0.4938 0.01145 0. 0. http://dx.6955 0. size<D. we should check that this code is reasonably efficient.3319 -0.6978<.099 0. 0.2591 -0. In[91]:= Out[92]= mat = RandomReal@1.4287 -0.6499. 80.6955.403233. 0. 81000. ReplaceElement@rmat.2575 -0. Timing@Det@matD. size<. "NêA"D êê MatrixForm Out[88]//MatrixForm= -0. 80.50 on Wed May 18 01:16:10 BST 2016.8398.4444 NêA 0. MatrixForm@mat2D Out[87]//MatrixForm= -0.D.5088 -0.11945 0.6978 0.099.2575 -0. 2<D ß "NAN"D D. "NêA". "NêA". -0.0589 -0.8398 -0. 0. -0.6052 0.9319 0.5088 -0. mat = RandomReal@1.4938.5332 0.5088. 80. 0. Downloaded from Cambridge Books Online by IP 157.8287. then inserts strings here and there.006 Cambridge Books Online © Cambridge University Press. êê Timing 80.4242 0.5924 Of course.8398 NêA 0.5924 ReplaceElement@mat2. 0.

b. done in a different way. 0. 88. ListD &L@ FoldList@Plus. In[6]:= split2@lis_. http://dx. a. 0. In Section 4. 5.and three-dimensional offlattice walks. a. or Inner. 2<< b. 4. Tally the frequencies with which distinct elements appear in a list. 2<. Divide up a list such that the length of each part is given by the second argument. Then do the same for two. Union@lisDD In[2]:= tally@8a. the median is given by the average of the middle two elements of lis. c<D Out[2]= In[3]:= Out[3]= 88a. 8b. . Ò2<D &. 8c. 6. a. 5. parts_D := Map@Take@lis. partsD. c. Ò1 + 81. 2. 3<.1D + 1. We list below a number of one-liner function definitions along with a very brief explanation of what these userdefined functions do and a typical input and output. In[4]:= In[5]:= Out[5]= split1@lis_.5. Rewrite CountChange to use a purely functional approach. 3<. c. 83. One of the best ways to learn how to write programs is to practice reading code.doi. 0. Rest@Ò1D. 0<D &. 3. Write a version of the function that computes Hamming distance by using Count to find the number of nonidentical pairs of corresponding numbers in two binary signals. 8Ò1. a. using transformation rules. 2.50. 3<. 1DD 6. 8b.2 we created a function CountChangeAlisE that took a list of coins and. random walk. Consider using Dot. 3<D 881.253.006 Cambridge Books Online © Cambridge University Press. Drop@Ò1. parts_D := HInner@Take@lis. c<D 88a. 7<. 9. Downloaded from Cambridge Books Online by IP 157. 2016 . 5. 8<. mD returns the survivor starting from a list of n people and executing every mth person. 3<. 8c. b. 10<< This is the same as the previous program.50 on Wed May 18 01:16:10 BST 2016. a. 7. Write an implementation of Hamming distance using the Total function and then compare running times with the other versions discussed in this chapter. a walk with step positions any real number between -1 and 1. Write a function that generates a one-dimensional off-lattice. that is. b. 2<< Tally@8a. 4. Create one rule for the case when lis has an odd number of elements and another rule for the case when the length of lis is even. Count@lis. b. returned the monetary value of that list of coins.8 Examples and applications 187 Exercises 1. In[1]:= tally@lis_D := Map@H8Ò .1017/CBO9780511972942. Create a function medianAlisE that computes the median of a one-dimensional list. so that survivor@n. partsDD split1@Range@10D. Extend the survivor function developed in this section to a function of two arguments. Partition@FoldList@Plus. b. 82. Deconstruct these programs to see what they do and then reconstruct them as compound functions without any pure functions. Ò D<L &. In the latter case. or Tally.

k. Extend the range of ReplaceElement developed in this section to accept a list of strings considered as nonnumeric matrix entries. p. u<< Finally. "q". InflammatoryResponse. w. q. In[11]:= Out[11]= NearTo@chars. o. nE that returns all elements of lis that are exactly n positions away from elem. http://dx.3. "BiologicalProcesses"D 8BloodCoagulation. create you own distance function (DistanceFunction ) and use it with the built-in Nearest to do the same computation. u. NearToAlis. "z"D 8a. 8n<E that returns all elements in lis that are within n positions of elem. Downloaded from Cambridge Books Online by IP 157. r. posD returns elements from expr whose positions pos are given by Position . elem. A Smith number is a composite number such that the sum of its digits is equal to the sum of the digits of its prime factors. s. 8False. For example.253.006 Cambridge Books Online © Cambridge University Press. Fibrinolysis. l. n. s. Given a list of expressions.Functional programming 188 8.50 on Wed May 18 01:16:10 BST 2016. For example: In[9]:= Out[9]= In[10]:= Out[10]= chars = CharacterRange@"a". Extract@expr.1017/CBO9780511972942. False<< You will also find it helpful to consider threading rules over the tuples using MapThread or Thread . q. You can create a list of truth values using Tuples . varsD that takes a logical expression such as AB and outputs a truth table similar to those in Section 2. o. Proteolysis< 10. True<. create a function NearToAlis. b. for example: In[7]:= Out[7]= ProteinData@"KLKB1". elem. For example. False<. x. Extend the visualization of PPI networks from this section by coloring vertices according to the biological process in which they are involved. 2D 88True. and so the sum of the digits of its prime factors is 2 + 2 + 3 + 7 + 1 = 15 which is equal to the sum of its digits. e. 11. True<. g. r. 8False. p. 8t<< Write a second j. y. The built-in ProteinData contains this information.doi. the prime factorization of 852 is 22 ÿ 31 ÿ 711 . lis. n. Two useful functions for these tasks are Position and Extract . In[8]:= Out[8]= Tuples@8True. t. m. "q". 9. v. f. 84<D 88m. Create a function TruthTable@expr. i. z< NearTo@chars. h. 2016 .50. t. 8 + 5 + 2 = 15. c. 8True. 12. d. Write a program to find all Smith numbers less than 10 000. each of which should be replaced by a column mean. 3D 88n<. False<.