List component assignment
3.5 Strings and characters
Characters are the objects that appear on the computer screen like “a”, “3”, or “!”. Uppercase and lowercase letters, numbers, punctuation marks, and spaces form the basic set of characters. A sequence of characters enclosed in double quotes is called a string.
In[1]:= Head "The magic words are squeamish ossifrage."
Out[1]= String
When Mathematica prints out a string, it appears without the quotes. In[2]:= "The magic words are squeamish ossifrage."
Out[2]= The magic words are squeamish ossifrage.
You can use the InputForm function to see these quotes.
In[3]:= InputForm "The magic words are squeamish ossifrage."
Out[3]//InputForm=
"The magic words are squeamish ossifrage."
A string is a value and, like other values (such as numbers and lists), there are built-in functions available to manipulate strings, similar to those for lists. Their operations are indicated by their names.
In[4]:= StringLength "The magic words are squeamish ossifrage."
Out[4]= 40
In[5]:= StringReverse "abcde"
Out[5]= edcba
In[6]:= StringTake "abcde", 3
Out[6]= abc
In[7]:= StringDrop "abcde", 1
In[8]:= StringPosition "abcde", "bc"
Out[8]= 2, 3
In[9]:= StringInsert "abcde", "t", 3
Out[9]= abtcde
In[10]:= StringReplace "abcde", "cd" "uv"
Out[10]= abuve
New in Version 5.1, you can use regular expressions in the functions you use to manipulate strings.
In[11]:= StringMatchQ "all in good time", RegularExpression "a. "
Out[11]= True
In[12]:= StringCases "abc1, abd2, bcd3", RegularExpression "a. ?\\d"
Out[12]= abc1, abd2
In addition to using built-in functions to manipulate a string, you can convert a string to a list of characters with the built-in Characters function.
In[13]:= Characters "abcde"
Out[13]= a, b, c, d, e
You can then use the list manipulating functions to alter the list or extract elements from the list.
In[14]:= Take %, 2, 3
Out[14]= b, c
Finally, you can change the resulting list back into a string using the built-in String Join function.
In[15]:= StringJoin %
Out[15]= bc
Another way to manipulate a string is to convert it to a list of character codes and then operate on the codes using mathematical functions. Each character in a computer’s character set is assigned a number, called its character code. Moreover, by general agree- ment, almost all computers use the same character codes, called the ASCII codes. In this code, the uppercase letters A, B, …, Z are assigned the numbers 65, 66, …, 90 while the lowercase letters a, b, …, z have the numbers 97, 98, …, 122 (note that the number of an uppercase letter is 32 less than its lowercase version). The numbers 0, 1, …, 9 are coded as
48, 49, …, 57 while the punctuation marks period, comma, and exclamation point have the codes 46, 44, and 33, respectively. The space character is represented by the code 32. Table 3.1 shows the characters and their codes.
Characters ASCII codes
A, B, …, Z 65, 66, …, 90 a, b, …, z 97, 98, …, 122 0, 1, …, 9 48, 49, …, 57 . period 46 , comma 44 exclamation 33 space 32
Table 3.1: ASCII character codes
Using the character code representation of characters, the following series of compu- tations changes a word from lowercase to uppercase.
In[16]:= ToCharacterCode "darwin"
Out[16]= 100, 97, 114, 119, 105, 110
In[17]:= % 32
Out[17]= 68, 65, 82, 87, 73, 78
In[18]:= FromCharacterCode %
Out[18]= DARWIN
This can be accomplished more succinctly using StringReplace. In[19]:= StringReplace "darwin", x_ ToUpperCase x
Out[19]= DARWIN
Or simply:
In[20]:= ToUpperCase "darwin"
Exercises
1. Convert the first character in a string (which you may assume to be a lowercase letter) to uppercase.
2. Given a string containing two digits, convert it to its integer value; so the string "73" produces the number 73.
3. Given a string containing two digits, convert it to its value as an integer in base 8; for example, the string "73" will produce the number 59.
4. Given a string of digits of arbitrary length, convert it to its integer value. (Hint: You may find that the Dot function is helpful.)
5. Create a Boolean function OrderedWordQ that returns True or False depending upon whether its argument is in alphabetic order. So OrderedWordQ["best"] would return True but OrderedWordQ["brag"] would return False. Then find all those words in the file dictionary.dat that are ordered according to this function.
Here is a platform-independent path to the dictionary file.
In[1]:= wordfile ToFileName $InstallationDirectory, "Documentation", "English", "Demos", "DataFiles" , "dictionary.dat"
Out[1]= C:\Program Files\Wolfram Research\Mathematica\5.1\ Documentation\English\Demos\DataFiles\dictionary.dat
This reads in the file using ReadList, specifying the type of data being read in as a Word.
In[2]:= words ReadList wordfile, Word ;
6. Create a function PalindromeQ[str] that returns a value of True if its argument
str is a palindrome; that is, if the string str is the same forward and backward. For
Programming in Mathematica is essentially a matter of writing user-defined functions that work like mathematical functions; when applied to specific values, they perform computations producing results. In fact, these functions can operate on arbitrary expressions, including other functions. This functional style of programming distin- guishes Mathematica from more traditional procedural languages like C and Fortran, and a facility at functional programming is essential for taking full advantage of
Mathematica’s powerful language to solve your computational tasks.
4.1 Introduction
Functions are objects that operate on expressions and output unique expressions for each input. We can think of functions as mathematicians do. For example, here is a definition for a function of two variables.
In[1]:= f x_, y_ : Cos x Sin y
You can evaluate the function for numeric or symbolic values. In[2]:= f , 1.6
Out[2]= 0.000426397
In[3]:= f ,
Out[3]= Cos Sin
Functions can be significantly more complicated objects. Below is a function that operates on functions. Like the function f above it takes two arguments, but, in this case, its arguments are a function or expression, and a list containing the variable of integration and the integration limits.
In[4]:= Integrate Exp I x , x, a, b
Out[4]=
This particular function can be also be called with a function and a variable. In[5]:= Integrate Exp I x , x
Out[5]=
x
Here is a function that also takes two arguments and operates on functions, but it returns a graphical object as its value.
In[6]:= Plot Sin x 2 Sin x , x, 0, 2
1 2 3 4 5 6 1 0.5 0.5 1 Out[6]= Graphics
Programming involves writing a set of instructions to be applied for some appropri- ate input. Whereas procedural programs provide a step-by-step set of instructions, func- tional programming involves the application of functions to their arguments. For example, here is a traditional procedural approach to switching the elements in a list of pairs.
In[7]:= lis , 1 , , 2 , , 3
Out[7]= , 1 , , 2 , , 3
In[8]:= temp lis;
Do temp i, 1 , temp i, 2 lis i, 2 , lis i, 1 ,
i, 1, Length lis ;
temp
Out[10]= 1, , 2, , 3,
We first allocate an empty array temp, of the same size as lis; then we put elements into temp one by one as we loop over lis; finally we return the value of temp.
Here is a simpler procedure using a structured iteration. In[11]:= Table lis i, 2 , lis i, 1 , i, 1, 3
And here is a functional approach to solving the same problem. In[12]:= Map Reverse, lis
Out[12]= 1, , 2, , 3,
This simple example illustrates several of the key features of functional program- ming. A functional approach often allows for a more direct implementation of the solution to many problems, especially when list manipulations are involved. Notice that the proce- dural approach required setting up a list structure and then looping over the list as i takes on successive values, whereas the functional approach simply applied the Reverse func- tion to the list directly.
Up to this point, we have described fairly simple functions and stayed focused on the built-in functions present in Mathematica. In this chapter we will first take a look at some of the most powerful and useful functional programming constructs in Mathematica and then discuss the creation of our own functions, using many of the list and string manipulat- ing functions discussed earlier. It is well worthwhile to spend time familiarizing yourself with these functions by playing around with them; for example, create various lists and apply built-in functions to them. Having a larger vocabulary of built-in functions will not only make it easier to follow the programs and do the exercises here, but will enhance your own programming skills as well.