Contents Previous Next Index
10 Input and Output
10.1 In This Chapter
Introduction
Input and output in the worksheet
Input and output with files
Reading and writing formatted data
Useful utilities
2-D math
10.2 Introduction
This chapter explores the ways in which you can read input and write output programmatically. Here are a few examples of I/O operations in Maple.
Example 1: An integral can be printed in various ways. The two outputs below show the integral in 2-D and 1-D representations, respectively.
y := Int(x^2, x=1..2);
y≔∫12x2ⅆx
lprint(y);
Int(x^2,x = 1 .. 2)
Example 2: The checkfile procedure defined below uses commands in the FileTools package to examine the properties of a file.
checkfile := proc(fname :: string) return FileTools:-Exists(fname) and FileTools:-IsReadable(fname); end proc:
Example 3: A Matrix is written to a file using the ExportMatrix command.
M := LinearAlgebra:-RandomMatrix(5, 4);
M≔
ExportMatrix("testfile", M);
67
Example 4: The sscanf command is used here to read three floating-point numbers from the string given as the first argument.
z := sscanf("X=123.4 Y=-27.9 Z=2.3E-5", "X=%f Y=%f Z=%f");
z≔123.4,−27.9,0.000023
The first example shows the difference between 1-D and 2-D output in Maple. Note that input can also be provided in both forms. In Maple, 1-D math is character-based, is available in all interfaces, and can be controlled by many of the basic I/O commands discussed in this chapter. Typeset or 2-D math is available only with the standard worksheet interface and is generally manipulated interactively using the Maple GUI tools. However, it can be controlled programmatically in a limited way.
Most of this chapter is devoted to the manipulation of files, which is the main way data is shared between Maple and external applications. Many of the file-processing commands also apply to interactive input and output, when 1-D mode is used. For example, the command for formatted writing, printf, produces output in a Maple worksheet or document. However, it is essentially identical to the fprintf command for printing to a file.
This chapter starts with a discussion of input and output in the worksheet, including some notes on using other interfaces. The next section covers manipulation of files. Tools for importing and exporting general files as well as those specially designed for numerical data are discussed. Later in the chapter, low-level commands for formatted reading and writing, along with other useful utilities, are shown. The chapter concludes with an explanation of 2-D math and how it can be customized programmatically.
10.3 Input and Output in the Worksheet
This section introduces common ways of reading from the keyboard and writing to the screen. In contrast, the following section discusses I/O through the use of files. There is some overlap between the two sections, as the keyboard and screen themselves can be considered files. This is explained further in the "Default and Terminal Files" section of the file_types help page.
Interfaces
Maple has several user interfaces, all described on the versions help page. In this chapter, it is assumed you are using either the standard worksheet interface or the command-line interface. Most of the I/O operations described here apply to either interface. The major exception is typeset or 2-D math, which is available only with the standard worksheet interface.
You can use the interface command to communicate with the user interface. It allows you to query or set certain user interface variables. This is one way of controlling the look of the output. Note that the interface command does not affect the actual computation. A few examples are shown below. A complete list of the variables is available on the interface help page.
The version variable returns the interface version, platform information, build date and build number.
interface(version);
Standard Worksheet Interface, Maple 2024.0, Linux, March 01 2024 Build ID 1794891
The prettyprint variable controls how Maple expressions are rendered as output.
interface(prettyprint=1): Diff(f(x), x);
Typesetting:-mstyle(DifferentialD, mathcolor = "#909090") ---------------------------------------------------------- fApplyFunction(x), Typesetting:-mstyle(DifferentialD, mathcolor = "#909090")x [ /[ d ] [ d ]\] [Typesetting:-mprintslash|[--- f(x)], [--- f(x)]|] [ \[ dx ] [ dx ]/]
interface(prettyprint=3): Diff(f(x), x);
ⅆⅆx⁢f⁡x
The rtablesize variable specifies the largest-sized rtable that will be displayed inline. If an rtable has a dimension that is larger than this integer, then it is displayed as a placeholder.
interface(rtablesize);
10,10
Matrix(5, 5, (i,j)->i+j);
Matrix(15, 15, (i,j)->i+j);
Interactive Output
By default, the output from a statement entered in the worksheet is automatically printed to the screen, unless the statement is terminated by a colon. In the previous section, you saw how to use the interface command to customize certain aspects of the output. Another way to adjust the output is to set the printlevel environment variable. The default value of printlevel is 1. When it is set to a higher value, additional information pertaining to procedure calls is printed. This is one way of tracing a procedure for debugging purposes. For more information about debugging programs, see Testing, Debugging, and Efficiency.
The print command prints Maple expressions using the current setting of the prettyprint interface variable. In the worksheet, the default output is 2-D math and in the command-line version, the default is a simulated math notation using text characters. Note that the print command returns NULL and thus the output cannot be regenerated with the ditto commands.
The print command is particularly useful in two situations. First, it can be used to print intermediate results calculated within a procedure. Normally, only the returned value of a procedure is printed when it is called.
p := proc(n) local i; for i to n do i^2; end do; end proc:
p(5);
25
q := proc(n) local i; for i to n do print(i^2); end do; end proc:
q(5);
1
4
9
16
The print command can also be used to print procedures and other expressions that follow last name evaluation rules. For more information, refer to the last_name_eval help page.
print(q);
procnlocali;foritondoprint⁡i^2end doend proc
The lprint command prints Maple expressions in a character-based notation that is similar to the format used for 1-D input. Like the print command, the value returned by a call to lprint is NULL, and the output cannot be recalled using the ditto operator. When the prettyprint interface variable is set to 0, Maple uses lprint to print all expressions to the interface.
lprint(expand(x+y)^5);
(x+y)^5
Another commonly used command is printf, which produces formatted output. This command will be discussed in Reading and Writing Formatted Data.
If you want to redirect all output that normally goes to the screen to a file, use the writeto and appendto commands. This is an easy way to log the input and output of a Maple session, particularly if you are using the command-line interface. In the standard worksheet interface, you can simply save the current worksheet or document. For more information on writing to files, see Input and Output with Files.
Interactive Input
Normally, input is passed to Maple procedures directly through the procedure's parameters. In the standard worksheet interface, input can also be provided through Maplets and components. For more information about these topics, see Programming Interactive Elements.
The readline and readstat commands are also available for interactive input, though these are less commonly used. The readline command reads the next line from the terminal or a file and returns it as a string, while the readstat command reads the next statement from the terminal and returns the value of that statement.
Customization
You can customize the prettyprinting of a function fnc in a limited way by defining a print/fnc procedure. In the following example, expressions of the form g(x) should be printed so that the argument is repeated three times in a list.
`print/g` := proc(x) [x, x, x] end proc:
g(b^2);
b2,b2,b2
g(5.8);
5.8,5.8,5.8
There is a similar facility for prettyprinting a module. If a module has an export or local named ModulePrint, then the result of the ModulePrint command is displayed instead of the module when a command in the module is executed. For more information, see Programming with Modules.
10.4 Input and Output with Files
This section covers input and output using files, which is recommended when you have a large amount of data to process. This also provides a way for Maple to share data with external applications. In this chapter, the term "file" is not limited to a disk file, but can include the default output stream to a terminal or worksheet output region. Below is a brief introduction to a few concepts related to files. For more detailed information, refer to the file and file_types help pages.
Text and binary files: The Maple I/O library works with both text files (streams of characters) and binary files (streams of bytes). The I/O commands allow you to specify the type of file and generally assume a text file if no information is given.
Read and write modes: At any given time, a file may be open either for reading or for writing. If you attempt to write to a file which is open for reading, Maple closes and reopens the file for writing. If you do not have permission to write to the file, then an error occurs.
The default and terminal files: The Maple I/O library treats the user interface as a file. The identifier default refers to the current input stream, the one from which Maple reads and processes commands. The identifier terminal refers to the top-level input stream, the current input stream when you started Maple. When Maple is run interactively, default and terminal are equivalent.
File names and descriptors: Maple I/O commands refer to files in one of two ways: by name (given as a string) or by descriptor. A file descriptor identifies a file after you have opened it using its name and offers slight advantages in terms of efficiency and flexibility. The commands described in this section accept either a name or a descriptor as the file identifier.
Current directory: If you create files using the examples in this chapter, the files are saved in the current directory. To query or set the current working directory, use the currentdir command.
Working with General Files
This section covers the manipulation of general files. If you are working with files of numerical data, it is recommended that you use the commands described in ImportMatrix and ExportMatrix.
There are two sets of commands that you can use. The first subsection below describes the basic top-level commands for file manipulation. Alternatively, you can use the FileTools package, which provides a simpler interface to the other commands and offers additional functionality. For most file operations, the FileTools package is recommended, but the two sets of commands are generally compatible and can be used interchangeably on a file.
The Maple I/O Library
Below is a description of commonly used commands in the Maple I/O library.
Opening and closing files
Before you can read from or write to a file, you must open it. When referring to files by name, this happens automatically with the first file operation. When you use descriptors, however, you must explicitly open the file first to create the descriptor. The fopen command takes as arguments the filename, a mode (READ, WRITE or APPEND) and optionally, the file type (TEXT or BINARY).
f := fopen("testfile", 'WRITE', 'TEXT');
When you are finished with a file, you can close it with the fclose command, which takes the file identifier as its argument. This operation ensures that all information is written to the disk. When you exit Maple or use the restart command, Maple automatically closes any open files, whether they were opened explicitly with fopen or implicitly through one of the other I/O commands.
Reading and writing lines of text
The readline command reads one newline-terminated line from a file and returns a string containing that line. The writeline command writes one or more strings to a file, separated with newline characters, and returns a count of the characters. If the file is not already open with type TEXT, then the readline or writeline command will open the file automatically.
writeline("testfile", "The first line", "The second line");
Reading and writing bytes
The readbytes command reads one or more or bytes from a file and returns a list of integers. Optionally, you can specify that the file is to be opened in text rather than binary mode, and in this case, a string is returned. You can also provide a previously created rtable to the readbytes command and it will return the data in the rtable. Similarly, the writebytes command writes bytes from a string or list to a file. More information about both commands can be found on their help pages.
Reading and writing formatted input and output
The fscanf command parses expressions from a file based on a format string. Similarly, the fprintf command prints expressions to a file based on a format string. Both commands are similar to the C standard library commands of the same names. Both fscanf and fprintf are described in greater detail in Reading and Writing Formatted Data.
Other file utilities
There are a number of other useful file utilities, including iostatus (obtain the status of an open file), fremove (remove a file), fflush (flush output), filepos (sets or returns the position), and feof (check if the current position is at the end). For more information about these commands, refer to their help pages.
Below is a simple example that uses a few of the commands introduced here. The file generated will be placed in your current working directory, which you can set with the currentdir command.
First, define a Vector of floating-point values.
V := Vector([1.20, 4.85, 6.23, 2.45, 7.99]):
n := LinearAlgebra:-Dimension(V):
Next, create a new file called prices1.txt and write a number of lines, one for each Vector entry.
fid := fopen("prices1.txt", 'WRITE', 'TEXT'):
writeline(fid, "List of Prices"): for i to n do fprintf(fid, "Item %d costs %.2f\n", i, V[i]): end do:
fclose(fid):
Now open the file again and read the values from each line, adding them up as they are read.
fid := fopen("prices1.txt", 'READ', 'TEXT'):
readline(fid):
pricesum := 0.: while not feof(fid) do t := fscanf(fid, "Item %d costs %f\n"): pricesum := pricesum + t[2]: end do:
Finally, reopen the file to append a line showing the sum of the prices.
fid := fopen("prices1.txt", 'APPEND', 'TEXT'):
fprintf(fid, "\nThe sum of the prices is: %.2f\n", pricesum):
If you encounter an error while using any of the I/O commands listed in this section, refer to the IO_errors help page for more information about the source of the error. Common mistakes include reading from a file that does not exist and writing to a file for which you do not have permission to alter.
The FileTools Package
The FileTools package is a collection of file manipulation utilities. It covers most of the functionality described in the previous section and provides an easy-to-use interface. It also contains a large number of additional commands that are useful when working with files.
The FileTools package contains two subpackages: FileTools:-Text and FileTools:-Binary. These subpackages contain commands to work with text files and binary files, respectively.
Some of the commonly used commands are listed below. A full list of commands is available in the FileTools help page.
The FileTools:-Text:-Open command allows a file to be opened, with options to indicate whether Maple can create the file if it does not already exist, overwrite it, or append to it. It returns a file descriptor. As with the situation described in the previous section, it is not always necessary to open a file before using it, as a file is automatically opened when you use a FileTools command to access it. The FileTools:-Text:-Close command closes a file and ensures all data is written to disk. When you exit Maple, all open files are automatically closed. The FileTools:-Text:-OpenTemporaryFile command causes a temporary file to be opened. Corresponding commands are available in the Binary subpackage: FileTools:-Binary:-Open, FileTools:-BinaryClose, and FileTools:-Binary:-OpenTemporaryFile.
Reading from and writing to binary files
The FileTools:-Binary:-Read and FileTools:-Binary:-Write commands are available for reading and writing binary data. Unlike the readbytes and writebytes commands, the FileTools commands support a number of hardware data types and allows the byte order to be specified. There is also a FileTools:-Binary:-CountBytes command for returning the total number of bytes left in a file.
Reading from and writing to text files
The FileTools:-Text subpackage has a large number of commands for reading and writing text. The FileTools:-Text:-Readline and FileTools:-Text:-Writeline commands read and write a line at a time. The FileTools:-Text:-ReadFile command reads all lines in a file at once.
The FileTools:-Text:-ReadFloat and FileTools:-Text:-WriteFloat commands offer simple ways to read and write a single float. The FileTools:-Text:-ReadNextFloat command is useful if you want to read the next float while ignoring all characters preceding it. The FileTools:-Text:-CountFloats command counts the number of floating-point numbers remaining in the file. Similar commands are available for integers, characters, and strings as well.
Checking and modifying properties of files
The FileTools package has commands that allow you to examine the properties of a file, such as FileTools:-Status, FileTools:-Exist, and FileTools:-AtEndOfFile. There are a number of additional commands that check if a file is open, readable, writable, lockable, or executable. The package also includes commands that return a file's size and position.
It is possible to modify files, by using, for example, the FileTools:-Rename and FileTools:-Remove commands. There are also commands for copying, locking, and unlocking files.
Performing directory operations
The FileTools package also includes commands to work with directories and file paths, such as FileTools:-ListDirectory, FileTools:-MakeDirectory and FileTools:-AbsolutePath.
The following example is similar to the one shown in the previous section using the basic I/O commands, but this time, you will use the FileTools package.
First, create a new file prices2.txt containing a title and a line for each of the values in V. Here, you can use the commands for writing strings, integers and floats, without worrying about specifying the formatting precisely.
with(FileTools:-Text):
fid := Open("prices2.txt", 'overwrite'):
WriteLine(fid, "List of Prices"): for i to n do WriteString(fid, "Item"); WriteInteger(fid, i, 'delim'=" "); WriteString(fid, "costs"); WriteFloat(fid, V[i], 'leftdelim'=" "): WriteLine(fid, "."); end do:
Close(fid);
Now, open the file again and read the floating-point values from each line. The CountLines and ReadNextFloat commands make this task easier, as you do not have to check for the end of file or explicitly read other characters in each line.
fid := Open("prices2.txt"):
ReadLine(fid):
pricesum := 0.: numlines := CountLines(fid): for i to numlines do ReadNextInteger(fid): pricesum := pricesum + ReadNextFloat(fid): end do:
Close(fid):
Finally, open the file again to append a line showing the sum of the prices.
fid := Open("prices2.txt", 'append'):
WriteLine(fid, "", "The sum of the prices is:"):
WriteFloat(fid, pricesum):
Importing and Exporting Numerical Data
The basic I/O commands and the FileTools package can be used to read from and write to any text or binary file. However, if the file that you want to read or write consists exclusively of numeric data, then it is much easier to use one of the commands designed for this type of file.
ImportMatrix and ExportMatrix
The ImportMatrix and ExportMatrix commands read and write data that can be stored in a Matrix or Vector.
These commands support different types of files, including some that are generated or recognized by other software applications. The formats supported are: MATLAB®, Matrix Market, comma-separated values (.csv), and generic delimited files. The source and target options are used to indicate the desired format.
Files created with MATLAB® versions 5, 6 or 7 can be imported. By default, the ExportMatrix command generates a MATLAB® Version 7 binary file, using data compression as described on the StringTools:-Compress help page, when the target=Matlab option is provided. However, it is possible to generate a Version 6 file without compression by adding the mode=v6 option. You can also read and write MATLAB® ASCII files using the mode=ascii option. Import and export of both dense and sparse Matrices are supported with MATLAB® format.
Matrix Market files are imported and exported using the MatrixMarket value for the source and target options. The Matrix Market coordinate and array formats are supported; the pattern format is not supported.
For .csv and general delimited files, the format option can be used to indicate whether the storage is dense or sparse. In the latter case, only the nonzero entries are present in the imported or exported file.
Below is a small example showing how ImportMatrix and ExportMatrix work with MATLAB® arrays. The file will be placed in your current working directory.
Generate two random Matrices and export them to a MATLAB® Version 6 file. The number of bytes written is returned by the ExportMatrix command.
A := LinearAlgebra:-RandomMatrix(3, 4, 'datatype'=float[8]);
A≔
B := LinearAlgebra:-RandomMatrix(2, 5, 'datatype'=float[8]);
B≔
ExportMatrix("testfile.mat", [A, B], 'target'='Matlab', 'mode'='v6');
432
Now, read the MATLAB® arrays back into Maple using the ImportMatrix command. It is not necessary to use the source and mode options in this case. The ImportMatrix command can automatically recognize MATLAB® binary files. With most text files (MATLAB® or otherwise), you will have to specify the source type.
M := ImportMatrix("testfile.mat");
Warning, format option not applicable to MATLAB binary files
M≔mat1,?,mat2,?
A sequence of two lists is returned, with each list containing a string and a Matrix. The string shows the name stored with each matrix in the MATLAB® file. The names are automatically assigned by the ExportMatrix command, but you can specify your own names with the arraynames option.
Now, export the Matrix A to a text file with values delimited by spaces.
ExportMatrix("anotherfile.txt", A, 'target'='delimited', 'delimiter'=" ");
282
Import the contents of the file back into Maple. In this case, it is necessary to specify the source and the character used as delimiter.
ImportMatrix("anotherfile.txt", 'source'='delimited', 'delimiter'=" ");
Notice that only a single Matrix is returned. Multiple Matrices can be exported to MATLAB®, but with other formats, only a single Matrix can be saved in a file. Also, only MATLAB® arrays have names associated with them.
Other Commands
The readdata command reads numeric data from a text file into Maple. The data in the file must consist of integers or floating-point values arranged in columns, separated by white space, and it is returned in a list or list of lists.
The writedata command writes numeric data from a Maple vector, matrix, list or list of lists into a text file. This command accepts an optional argument in the form of a procedure that allows you to control the formatting of the output.
Files Used by Maple
In additional to the general files that can be manipulated by the I/O commands described earlier in this section, several other files are used implicitly by Maple. A few are described briefly below. For more information, refer to the file help page.
Maple language files
A Maple language file contains statements conforming to the syntax of the Maple language. These are the same as statements that can be entered interactively. Any filename can be used for a Maple language file, but the name cannot end with ".m". The standard file extension for Maple language files is ".mpl".
Maple language files can be created using a text editor or the save statement. Maple procedures and complex scripts of commands are usually written in a text editor, while the save statement is used to save results or procedures that were entered into Maple interactively.
Maple language files may be read using the read statement. The statements within the file are read as if they were being entered into Maple interactively, except that they are not echoed to the screen unless the echo interface variable has been set to 2 or higher.
Maple includes a preprocessor modeled on the C preprocessor and Maple language files may include preprocessor directives such as $include and $define.
Internal format files
Maple internal format files are used to store expressions compactly. Expressions stored in this format can be read by Maple faster than those stored in the Maple language format. These files are identified by filenames ending with the two characters ".m" (or ".M" on platforms where filenames are not case-sensitive).
Like Maple language files, Maple internal format files are read and written using the read and save statements. The presence of the ".m" ending in the filename specifies that the file is an internal format file, and not a language file.
Library archives
Maple uses library archive files to store collections of internal format files. These files end with the extension ".mla" (or, for older library archive files, with extension ".lib"). For more information about creating Maple libraries, see Writing Packages.
Workbook files with the extension ".maple" can be used to store collections of worksheets, documents, maple code, images, data files and more.
Help databases
A Maple help database is a file that stores a collection of files representing help pages in the Maple help system. It contains the information required to index, navigate, and search the help system, and its filename has the extension ".help". For more information, refer to the worksheet/reference/helpdatabase help page.
Worksheet files
If you are using Maple with a graphical user interface, you can save your worksheet. In the standard worksheet interface, files are identified by names ending with ".mw". In the classic worksheet interface, files end in ".mws". Both types of files are portable between the graphical user interfaces on different platforms.
Maplet Files
Maple worksheets can be saved as ".maplet" files. The MapletViewer runs such files independent of the Maple worksheet environment.
10.5 Reading and Writing Formatted Data
The scanf and printf Commands
The scanf and printf commands allow you to read from and write to the terminal using a specified format. The formatting information is provided by a format string. Below is an example showing how the printf command is used to display floating-point values.
Enter the following Vector of values:
V := Vector([.8427007929, .9953222650, .9999779095, .9999999846, 1.000000000]);
V≔
Print each value on a single line, preceded by an integer indicating its position. The format string is the first argument to the printf command. This string consists of two conversion specifications, "%d" and "%.2e", along with other characters to be printed, including the newline character "\n". The first conversion specification indicates that the first argument following the format string should be printed as an integer. The second conversion specification indicates that the second argument following the format string should be printed in scientific notation, with two digits after the decimal point.
for i to LinearAlgebra:-Dimension(V) do printf("%d%12.2e\n", i, V[i]); end do;
1 8.43e-01 2 9.95e-01 3 1.00e+00 4 1.00e+00 5 1.00e+00
The scanf and printf commands belong to a family of related commands that provide formatted I/O capabilities. The other commands will be discussed later in this chapter. These commands are based on similarly named functions from the C programming language library.
For example, the sscanf command below reads an integer, a space, a character, and a floating-point value from the string given as the first argument. The conversion specifications, "%d", "%c" and "%f", will be explained in the next section.
sscanf("892 123.456E7","%d %c%f");
892,1,2.3456×108
Format Strings
As you saw in the previous examples, the format string passed to scanf or printf specifies exactly how Maple is to parse the input or write the output. It consists of a sequence of conversion specifications that may be separated by other characters.
First, consider the specification for the scanf command, which has the format shown below. What follows is a brief explanation of the specification. For more information, refer to the scanf help page.
%[*][width][modifiers]code
The character "%" begins each conversion specification.
The optional character "*" indicates that the item scanned is to be discarded and not returned as part of the result.
The optional width indicates the maximum number of characters to be scanned for this object. You can use this to scan one larger object as two smaller objects.
The optional modifier affects the type of value to be returned. The most common of these is "Z", which, when preceding any of the numeric format codes, indicates that a complex value is to be scanned.
Several format codes are available for use with scanf. A few of the more commonly used ones are mentioned here.
"d" -- integer
"f" -- floating-point number
"c" -- character
"s" -- string
"a" -- Maple expression
The specification for the printf command is similar to that for scanf. The differences are summarized here. For more information, refer to the printf help page. The specification has the following format.
%[flags][width][.precision][modifiers]code
As with scanf, the conversion specification for printf begins with "%". The optional width and modifiers are similar to those described earlier. The width value indicates the minimum number of characters to output for the field.
The optional flag can be one of several characters affecting how numeric values are displayed. For example, the flag "+" indicates that signed numeric values are output with a leading "+" or "-" sign.
The format codes for printf are similar to those for scanf. One notable difference is that, while "e" and "g" are equivalent to "f" for scanf, they produce different output in printf. The code "e" causes a numeric value to be printed in scientific notation, while output using the code "g" uses one of integer, fixed-point or scientific notation, depending on the numeric value.
The scanf and printf commands can also be used to print rtables. For more information about the flags used for this purpose, refer to the rtable_printf help page.
Related Commands
Several commands are related to scanf and printf:
fscanf and fprintf
These commands read from and write to a file instead of the terminal. They take a filename or descriptor as an additional argument, but otherwise use the same calling sequence as scanf and printf.
sscanf and sprintf
These commands read from and write to a string (which is then returned) instead of the terminal. The sscanf command takes a string as an additional argument, but otherwise these commands use the same calling sequence as scanf and printf.
nprintf
This command is the same as sprintf except that it returns a Maple symbol instead of a string.
All these commands are described fully on the scanf and printf help pages.
10.6 Useful Utilities
This section describes other tools that are useful for input and output.
The StringTools Package
The StringTools package is a collection of utilities for manipulating strings. These commands are frequently used in conjunction with the basic input and output commands, for analyzing or converting data that is read or written. The StringTools package includes numerous commands; for brevity, we will describe only a few commands that may be of interest to users performing input/output operations in Maple. These include commands for
converting the case of characters (e.g., StringTools:-LowerCase)
performing character class tests (e.g., StringTools:-HasDigit)
comparing strings (e.g., StringTools:-IsPrefix)
doing pattern-matching and text searching (e.g., StringTools:-Substitute)
handling whitespace (e.g., StringTools:-TrimRight)
Two commands that are relevant to file I/O are StringTools:-Compress and StringTools:-Uncompress. The first command uses an algorithm from the zlib library to compress the input into a lossless and more compact format, while the second reverses the process. These commands are compatible with the commands for reading and writing bytes described in Input and Output with Files.
For more information about the zlib library, visit http://www.zlib.net.
Conversion Commands
Some additional commands may be useful when you are performing input and output operations in Maple.
The convert/bytes help page shows how to transform strings into bytes using the convert command.
The parse command allows you to parse a string as a Maple statement. For example, the following command parses the given string, evaluates it, and returns the expression 4*x^2.
parse("x^2+3*x^2");
4⁢x2
10.7 2-D Math
Typeset or 2-D math is available with the standard worksheet interface. Normally, input and output of 2-D math is done interactively using the Maple GUI tools. However, certain aspects of the input and output can be controlled programmatically in a limited way.
There are two available modes for typesetting: standard and extended. The mode can be changed by using the interface command. The following command shows the current setting in your worksheet or document:
interface(typesetting);
extended
Standard typesetting uses default rules for displaying expressions. With extended typesetting, the rules can be customized using the Typesetting Rule Assistant (TypesettingRuleAssist) or exports from the Typesetting package. The Typesetting Rules Assistant and the Typesetting package exports can also be used to adjust how 2-D input is parsed, regardless of the typesetting mode used for output.
The Typesetting Package
The Typesetting package provides commands for programmatically customizing extended typesetting output in certain situations and for controlling how particular 2-D expressions are parsed. It also includes internal-use commands that are not intended for general use. Additionally, the package exports a number of names that act as Maple typesetting tags similar to MathML tags.
The commands available to users are described on the Typesetting help page. A subset of the commands are listed below:
Typesetting:-Settings: adjust general extended typesetting settings, such as whether dot notation for derivatives is used and whether functions such as 2(x) should be interpreted as implicit multiplication.
Typesetting:-Suppress: suppress dependencies of functions (so that f can be interpreted as f⁡x, for example).
Typesetting:-EnableTypesetRule, Typesetting:-EnableParseRule and Typesetting:-EnableCompletionRule: control specific typesetting, parsing and command-completion rules.
Typesetting:-UseSymbolForTypeset: control the display of operator symbols.
Extended typesetting output is produced by the Typeset command. When this command is called, an unevaluated function is returned. This output, which is recognized by the Maple GUI, is not intended to be altered by users. Because the structure is meant for internal use, the tag names and format of the structure may change from one Maple release to another.
lprint(Typesetting:-Typeset(BesselJ(v, x)));
Typesetting:-mrow(Typesetting:-mi("BesselJ",fontstyle = "normal"),Typesetting:- mo("⁡"),Typesetting:-mfenced(Typesetting:-mi("v"),Typesetting:-mi ("x")))
Additional Tips
Users are discouraged from manipulating the typesetting structures created for internal use. However, in rare circumstances, it may be useful to call the Typesetting:-Typeset command. For example, standard typesetting mode is generally used for typeset text in plots. Extended typesetting output produced by the Typeset command may be passed to plots inside the typeset structure. For more information, see Typesetting.
Occasionally, you may find it necessary to manipulate a typeset expression programmatically without having the expression evaluate. For example, you want to print 12+13 without having it evaluate to 56, or you want to use x+, which gives an error when evaluated in Maple. In these situations, it is useful to create an atomic variable. To do this, you must be working in the standard worksheet interface. Enter the expression in the input line, select it and then use the 2-D math context menu to convert to an atomic variable. If you lprint the result, you will see a name (such as `#mrow(mi("x"),mo("+"))`, for x+) that can now be used within a Maple program written in 1-D math.
10.8 Exercises
Write a loop (with a single statement in its body) that prints strings listing the cubes of the integers 1 to 10.
Create a file in a text editor that contains the following lines.
x := 1; # valid input line
if := 2;} # invalid assignment
y := 3; # valid input line
two words := 4; # invalid assignment
Save the file. In a Maple session, open the file by using the read statement. Observe how Maple reacts to invalid statements.
Create a data file in a text editor that contains the following information.
1 2 3
4 5 6
Save the file. Read this file into a Maple session, convert the data to a list, and reverse its order. Write the reversed data in the same format to a different file.
Download Help Document