% Length nums
2.3 Predicates and Boolean operations
Predicates
When working with data sets, you are often presented with the problem of extracting those data points that meet certain criteria. Similarly, when you write programs, oftentimes what to do next at any particular point in your program will depend upon some test or condition being met. Every programming language has constructs for testing data or conditions.
Some of the most useful such constructs are called predicates. Apredicate is a function that returns a value of true or false depending upon whether its argument passes a test. For example, the predicate PrimeQ tests for the primality of its argument.
In[1]:= PrimeQ 144
Out[1]= False
Other predicates are available for testing numbers to see whether they are even, odd, integral, and so on.
In[2]:= OddQ[21]
Out[2]= True
In[3]:= EvenQ[21]
Out[3]= False
In[4]:= IntegerQ[5/9]
Out[4]= False
TheNumericQ predicate tests whether its argument is a numeric quantity. Essen-tially, NumericQ[x] givesTrue wheneverN[x] evaluates to an explicit number.
In[5]:= NumericQ
Out[5]= True
In[6]:= NumericQ
Out[6]= False
This is distinct from a related function,NumberQ, which evaluates toTrue whenever its argument is an explicit number (that is, has head one of Integer, Rational, Real, Complex).
In[7]:= NumberQ 3.2
Out[7]= True
In[8]:= NumberQ
Out[8]= False
Many other predicates are available for testing if an expression is an atom, a list, a matrix, a polynomial, and much more.
In[9]:= AtomQ "string"
In[13]:= IntervalMemberQ Interval 3, 4 ,
Out[13]= True
Relational and logical operators
Another type of predicate that is commonly used in programming are relational operators.
These are used to compare two or more expressions and return a value ofTrue orFalse.
The relational operators in Mathematica are Equal ( ), Unequal ( ), Greater (>), Less (<),GreaterEqual( ), and LessEqual ( ). They can be used to compare num-bers or arbitrary expressions.
In[14]:= 7 5
Out[14]= False
In[15]:= Equal 3, 7 4, 6
Note that the relational operators have lower precedence than arithmetic operators.
The second example above is interpreted as 3 (7-4) and not as (3 7)-4. Table 2.1 lists the relational operators and their various input forms.
StandardForm Functional form Meaning
x y Equal x,y equal
x y Unequal x,y unequal
x y Greater x,y greater than
x y Less x,y less than
x y GreaterEqual x,y greater than or equal x y LessEqual x,y less than or equal Table 2.1: Relational operators
The logical operators (sometimes known as Boolean operators) determine the truth of an expression based on Boolean arithmetic. For example, the conjunction of two true statements is always true.
In[17]:= 4 5 && 8 1
Out[17]= True
The Boolean operation “and” is represented inMathematica byAnd, with shorthand notation && or . Here is a table that gives all the possible values for theAnd operator.
(The function TruthTable is developed in Chapter 10.)
In[18]:= TruthTable A B, A, B
Out[18]//DisplayForm=
The logical “or” operator, represented byOr and with shorthand notation|| (or ), is true when either of its arguments is true.
In[19]:= 4 3 3 excludes the possibility that it isboth cold and hot. The logicalOr is inclusive in the sense that ifA and B are both true, thenA||B is also true.
In[21]:= True True
Out[21]= True
Mathematica also contains an operator for the exclusive or,Xor.
In[22]:= Xor True, True
Out[22]= False
In[23]:= Xor True, False
Out[23]= True
Table 2.2 shows the logical operators and their input forms.
StandardForm Functional form Meaning
x Not x not
x y Unequal x,y unequal
x&&y And x,y and
x y Or x,y or
x y && x&&y Xor x,y exclusive or Table 2.2: Logical operators
Introduced in Version 4 ofMathematica are thebitwise logical operators. These func-tions operate on integers as binary bits. For example, BitOr[x,y] gives the integer whose binary representation has 1s wherever the binary representation of x ory has 1s. Here is the bitwise OR of 21 and 19, given in binary form.
In[24]:= BaseForm BitOr 2^^10101, 2^^10011 , 2
Out[24]//BaseForm=
101112
Similarly,BitXor[x,y] gives the integer with 1s at positions where either x ory have 1s, but not both.
In[25]:= BaseForm BitXor 2^^10101, 2^^10011 , 2
Out[25]//BaseForm=
1102
Functional form Meaning
BitAnd x,y bitwise AND ofxandy BitOr x,y bitwise OR ofxandy BitNot x bitwise NOT ofx BitXor x,y bitwise XOR ofxandy Table 2.3: Bitwise operators
In Chapter 4 we will look at an application of bitwise operators to an example involving error-correcting codes: the computation of Hamming distance.
Exercises
1. Create a predicate function that returns a value of True if its argument is between 1 and 1.
2. Write a predicate function NaturalQ[n] that returns a value of True ifn is a natural number and False otherwise; that is,NaturalQ[n] is True ifn is among 0, 1, 2, 3, ….
3. Create a predicate function SubsetQ[lis1,lis2] that returns a value of True iflis1 is a subset of lis2. Remember: the empty set {}, is a subset of every set.
2.4 Attributes
All functions inMathematica have certain properties, calledattributes. These attributes can make a function commutative or associative, or they may give the function the ability to be threaded over a list. The attributes of any function are displayed with theAttributes function.
In[1]:= Attributes Plus
Out[1]= Flat, Listable, NumericFunction,
OneIdentity, Orderless, Protected
TheFlat attribute indicates that this function (Plus) is associative. That is, given three elements to add, it does not matter which two are added first. In mathematics, this is known asassociativity and is written asa b c a b c. InMathematica this could be indicated by saying that the two expressions Plus[a, Plus[b, c]] and Plus[
Plus[a, b], c] are equivalent to the flattened formPlus[a, b, c]. When Mathe-matica knows that a function has the attribute Flat, it writes it in flattened form.
In[2]:= Plus Plus a, b , c
Out[2]= a b c
The Orderless attribute indicates that the function is commutative; that is, a b b a. This allowsMathematica to write such an expression in an order that is useful for computation. It does this by sorting the elements into acanonical order. For expressions consisting of letters and words, this ordering is alphabetic.
In[3]:= t h i n
Out[3]= h i n t
Sometimes a canonical order is readily apparent.
In[4]:= x3 x5 x4 x2 1 x
Out[4]= 1 x x2 x3 x4 x5 Other times, it is not so apparent.
In[5]:= x3y2 y7x5 y x4 y9x2 1 x
Out[5]= 1 x x4y x3y2 x5y7 x2y9
When a symbol has the attributeProtected, the user is prevented from modifying the function in any significant way. All built-in operations have this attribute.
Functions with the attributeOneIdentity have the property that repeated applica-tion of the funcapplica-tion to the same argument will have no effect. For example, the expression
Plus[Plus[a, b]] is equivalent to Plus[a, b], hence only one addition is performed.
In[6]:= FullForm Plus Plus a b
Out[6]//FullForm=
Plus a, b
The other attributes for thePlus function, (Listable and NumericFunction) will be discussed in later chapters. Consult the manual (Wolfram 2003) for a complete list of theAttributes that symbols can have.
Although it is unusual to want to alter the attributes of a built-in function, it is fairly common to change the default attributes of a user-defined function. For example, suppose you had a function which you wanted to inherit the Orderless attribute. Without explicitly setting that attribute, the function does not reorder its arguments.
In[7]:= f x, a, m
Out[7]= f x, a, m
TheSetAttributes function is used to change the attributes of a function. Explicitly setting f to have theOrderless attribute causes its arguments to be automatically sorted.
In[8]:= SetAttributes f, Orderless
In[9]:= f x, a, m
Out[9]= f a, m, x
We will see a practical use of SetAttributes in Section 5.3.
The list is the fundamental data structure used in Mathematica to group objects together. A very extensive set of built-in functions is provided by Mathematica to manipulate lists in a variety of ways, ranging from simple operations, such as moving list elements around, to more sophisticated operations, such as applying a function to a list. We also discuss working with strings, as their structure and manipulation is so similar to lists.
3.1 Introduction
Many computations involve working with a collection of objects. For example, abstract mathematics deals with operations on arbitrary sets, represented notationally, but also conceptually, as lists.
In[1]:= a, b, c c, d, e
Out[1]= a, b, c, d, e
In[2]:= a, b, c c, d, e
Out[2]= c
Data, in Mathematica, is represented using lists. A large collection of functions is available for manipulating and analyzing lists of data. For example, you can sort any set of data.
In[3]:= Sort 4, 16, 1, 77, 23
Out[3]= 1, 4, 16, 23, 77
You can extract elements of a dataset based on some criteria. Here we select those numbers from a list that are greater than 0.
In[4]:= Select 4.9239, 1.24441, 0.80388, 3.27761 , Positive
Out[4]= 4.9239, 3.27761
Working with such collections of objects requires that the objects (also called data objects) be gathered together in some way. There are a variety of structures that can be used
to store data objects in a computer. The most often used data structure inMathematica is thelist. This is created using the built-inList function which has the standard input form of a sequence of arguments separated by commas and enclosed in braces.
arg1,arg2, …,argn
Lists are used throughout Mathematica, not only to represent a collection of data elements, but also to delineate a range of values for some variable or iterator. For example, the second argument to theTable function is a list that specifies the iterator variable and the values that it should range over.
In[5]:= Table i2, i, 1, 5
Out[5]= 1, 4, 9, 16, 25
Similarly, the plotting functions use lists to specify the range over which a variable should be evaluated.
In[6]:= Plot Sin x , x, 0, 2 ;
1 2 3 4 5 6
1 0.5 0.5 1
Internally, lists are stored in the functional form using theList function with some arbitrary number of arguments.
List arg1,arg2, …,argn
For example, using FullForm we can view the internal representation of the list {a,b,c}.
In[7]:= FullForm a, b, c
Out[7]//FullForm=
List a, b, c
The arguments of theList function (thelist elements) can be any type of expression, including numbers, symbols, functions, character strings, and even other lists.
In[8]:= 2.4, f, Sin, "ossifrage", 5, 3 , ,
Out[8]= 2.4, f, Sin, ossifrage, 5, 3 , ,
Elements in lists can be rearranged, sorted, removed, new elements added, and operations performed on select elements or on the list as a whole. In fact, lists are such general objects inMathematica that they can be used to represent a vast array of objects.
In this chapter, we will demonstrate the use of built-in Mathematica functions to manipulate lists in various ways. In cases where the operation of a function is relatively straightforward, we will simply demonstrate its use without explanation (the on-line Help system and the The Mathematica Book (Wolfram 2003) should be consulted for more detailed explanations of all of the built-in functions). The underlying message here is that almost anything you might wish to do to a list can be accomplished using built-in func-tions. It is important to have as firm a handle on these functions as possible, since a key to good, efficient programming in Mathematica is to use the built-in functions whenever possible to manipulate list structures.