The utils package
The utils package: A Demo Tour

This worksheet demonstrates the capabilities of the various functions included in the utils package. You need utils v1.11 or higher.

Contents

Online help

> restart:

> with(utils);

 [Makehelp, Write, WriteLn, addlib, addtbl, all, append, ascribe,
    assumed, cartprod, closefiles, count, ctime, date, dec,
    delete, dellib, deltbl, dir, entry, extract, fexists, flength,
    flines, fname, fnumber, getindets, haskey, inc, include,
    insert, isfopen, items, itemsFormStr, ladjust, lbound, leval,
    li, liblist, load, ls, lstrip, mSearchText, man, msearchtext,
    neval, nopsx, openfiles, prepend, prop, radjust, readlines,
    reinit, remember, repeat, replace, reshape, reverse, rewind,
    rstrip, scribe, shape, showif, size, spaces, strip, subdivide,
    swapcase, sysinfo, textfile, toLower, toUpper, ubound,
    vartrack, vp, wait, whatRelease, whichlib]

For information on the various utils functions available, type

> ?utils

to get a list of contents.

Sequences, lists, and sets

The utils package includes functions to add elements at specific positions,

Suppose you want to add an element a to a list L:

> L := [1, 2, 3];

L := [1, 2, 3]

To put the elements a, b at the beginning of that list, you would have to input:

> [a, op(L)];

[a, 1, 2, 3]

Alternatively, you may use utils/prepend to do this:

> prepend(a, L);

[a, 1, 2, 3]

Likewise, utils/append appends one or more items to a sequence, list, or set:

> append(a, L);

[1, 2, 3, a]

To reverse the order of the elements in a sequence, list or set, use utils/reverse :

> reverse(L);

[3, 2, 1]

This could be also done with seq (however, utils/reverse is much faster):

> [seq(L[nops(L) - n], n=0 .. nops(L) - 1)];

[3, 2, 1]

utils/insert inserts an item at a given position:

> s := a, b, c, a, 1, 2;

s := a, b, c, a, 1, 2

> insert(4=d, s);

a, b, c, d, a, 1, 2

Normally you would have to enter:

> op(subsop(4=(d, s[4]), [s]));

a, b, c, d, a, 1, 2

utils/count determines the number of times an element is included in a sequence or list (or set):

> count(a, s);

2

> count(-1, s);

0

To convert a list L to a list of lists, use utils/subdivide . For example if a list of six elements is to be reordered to a list of two lists with three elements each, type:

> L := [seq(n, n=1 .. 6)];

L := [1, 2, 3, 4, 5, 6]

> subdivide(L, 2, 3);

[[1, 2, 3], [4, 5, 6]]

Strings:

Although Maple is a computer algebra system, it can also manipulate strings, which is also useful to process textfiles.

utils/extract returns parts of a string. Suppose you would like to extract the first character in string str and the substring from the 12th to the 21st character:

> str := "N   1       0  4 42.0  27 26  0 13.40  4548";

str := "N   1       0  4 42.0  27 26  0 13.40  4548"

> extract(str, 1, 12 .. 21);

"N 0  4 42.0"

utils/delete deletes substrings from a string:

> delete(str, 1, 12 .. 21);

"   1        27 26  0 13.40  4548"

utils/include inserts a substring at a given position.

> include("123", "abcdefgh", 1);

"123abcdefgh"

> include("123", "abcdefgh", 4);

"abc123defgh"

utils/replace replaces a substring by another substring:

> replace(`Dieses ist ein Text`, `ein`=`a`, `ist`=`is`, `Text`=`text`, `Dieses`=`This`);

This is a text

utils/items returns the single words in a string. The words may be optionally converted to Maple expressions.

> str1 := "1 2 3.5 a exp(2)";

str1 := "1 2 3.5 a exp(2)"

> items(str1);

["1", "2", "3.5", "a", "exp(2)"]

> items(str1, parse);

[1, 2, 3.5, a, exp(2)]

utils/itemsFormStr reads a string and returns the corresponding format string to be used by sscanf , scanf, or fscanf.

> str2 := "1 2 3 4":

> itemsFormStr(str2);

"%a %a %a %a"

> format := itemsFormStr(str2, "%d");

format := "%d %d %d %d"

> sscanf(str2, format);

[1, 2, 3, 4]

Contrary to searchtext and Searchtext, which returns the first position in a string a substring has been found, mSearchText and msearchtext return all positions.

> msearchtext(" ", str2);

2, 4, 6

If you would like leading or trailing whitespaces in a string, use utils/lstrip or utils/rstrip respectively; utils/strip combines the functionality of both functions.

> str3 := "   123   ":

> lstrip(str3);

"123   "

> rstrip(str3);

"   123"

> strip(str3);

"123"

utils/spaces returns a string of n whitespaces. utils/repeat is a more general version and repeats a string n times.

> spaces(10);

"          "

> repeat(" ", 10);

"          "

utils/ladjust left-justifies converts an expression to a string and returns a string that is at least n characters wide, padding the string with whitespaces untill the given width. radjust right-justifies a string.

> str4 := ["-2.01", "0.08", "103.45"]:

> for i in str4 do
>    lprint(radjust(i, 10))
> od;

"     -2.01"
"      0.08"
"    103.45"

utils/toLower and utils/toLower convert strings to lower or upper case, resp.

> toLower(`tHIS iS A tEXT`);

this is a text

> toUpper(%);

THIS IS A TEXT

utils/swapcase converts lowercase letters to uppercase letters and vice versa.

> swapcase(`Maple Worksheet For Release 5.`);

mAPLE wORKSHEET fOR rELEASE 5.

New string types check have b een implemented: type/lowercase , type/uppercase, type/alphabetic, type/numericstring, type/alphanumeric, type/specialchar, type/hexdigits, type/octdigits are special string types.

> type(`Maple V`, lowercase);

false

> type(`Maple V`, alphabetic);

true

> type(`1A`, hexdigits);

true

> type(`0.4`, numericstring);

true

Tables and Arrays:

Currently, three functions are available for tables:

utils/addtbl and utils/deltbl add or delete entries in a table.

> addtbl(T, 0=Pi, 1=Pi/2);

 table([
    0 = Pi
    1 = 1/2 Pi
    ])

utils/haskey check whether a table or array has a specified key.

> haskey(T, 0);

true

> haskey(T, 2);

false

utils/entry returns the entry to a specific key.

> entry(T, 0);

[Maple Math]

> combinat[bell];

[Maple Math]

> entry(combinat, bell);

readlib('combinat/bell')

utils/reshape creates or reshapes an array.

> A := reshape([[1, 2, 3], [4, 5, 6]]);

[Maple Math]

> reshape(A, 3, 2);

[Maple Math]

utils/lbound and utils/ubound determine the lower and upper bounds of array.

> lbound(A);

1, 1

> ubound(A);

2, 3

utils/shape returns the extents of an array whereas utils/size returns the number of elements in an array (optionally in a given dimension).

> shape(A);

2, 3

> size(A);

6

> size(A, dim=1);

2

> size(A, dim=2);

3

utils/all checks whether all array elements satisfy a condition:

> all(A > 0);

true

> all(A < 7);

true

> all(A > -1);

true

> all(A = 0);

false

utils/nopsx is an extended nops function also returning the number of entries in an array or table.
> A := array(1 .. 2, 1 .. 3, [[1, 2], [3, 4]]);

[Maple Math]

> nopsx(A);
4

Input/Output:

There are various functions in the utils package that facilitate file reading or writing or for displaying text on screen.

utils/Write and utils/WriteLn write text to the screen without the limitations of lprint/print, so no commas or whitespaces are printed

> e := 2.718:

> lprint(`The result is: `, e);

The result is:    2.718

> WriteLn(`The result is: `, e);

The result is: 2.718

To write an algebraic expression to files in R4 and R5 with writeline, it first has to be converted to a string; utils/scribe , however, works like the old R3 function writeln which can be passed any expression(s) to be written to a file (or screen).

> writeline(default, 1, 2, exp(2));

Error, (in writeline) string expected

> writeline(default, cat(op(map(convert, [1, "   ", 2, "   ", exp(2)], string))));

1   2   exp(2)

15

> scribe(default, 1, 2, exp(2));

1   2   exp(2)

utils/ascribe appends a line to an existing file (or creates it):

> fn := "c:/test.txt":

> ascribe(fn, 1, 2, exp(2));

> ascribe(fn, Pi, x, 1/2);

> fclose(fn);

utils/readlines reads in an entire textfile line by line and returns the lines as a list of strings (or a table).

> readlines(fn);

["1 2 exp(2)", "Pi x 1/2"]

> map(items, %, parse);

[Maple Math]

utils/fexists checks for the existence of a file.

> fexists(fn);

true

Determine its file size with utils/flength :

> flength(fn);

30

utils/isfopen determines whether a file is open.

> isfopen(fn);

false

utils/openfiles returns all open files.

> openfiles();

> fopen(fn, READ):

> fd := fopen(`c:/text.txt`, WRITE):

> openfiles();

0 = "c:/test.txt", 1 = "c:/text.txt"

utils/closefiles closes one or more open files immediately.

> closefiles(0);

> openfiles();

1 = "c:/text.txt"

The name closeall closes all files that are open.

> closeall;

> openfiles();

The following functions print the contents of Maple libraries or file directories. They work only on MS Windows platforms.

> liblist(`e:/maplev5/update`);

convert/hypergeom.m           1998-04-30 16:10    46355  5432
convert/piecewise.m           1998-04-30 16:10    40077  6278
convert/plot2d3d.m            1998-04-30 16:10    51787   256
discont.m                     1998-04-30 16:10    62976  7843
int/definite/polynom.m        1998-04-30 16:10    55942   578
[etc.]

> ls(`e:/maplev5/update`);

Datentrger in Laufwerk E: ist DRIVE_E
Datentrgernummer: 14A9-70A5

Verzeichnis von e:\maplev5\update

20.10.98  21:12         <DIR>          .
20.10.98  21:12         <DIR>          ..
20.10.98  21:11                  2.624 index.txt
30.04.98  15:38                 12.288 maple.ind
30.04.98  15:38                 84.250 maple.lib
               6 Datei(en)         99.162 Bytes
                            220.708.864 Bytes frei

> dir(`e:/maplev5/update`);

Error, (in dir) Please assign _MapleOS with the name of your operating system
For UNIX: _MapleOS := 'UNIX'; for Windows 95 and NT: _MapleOS := 'Win'

> _MapleOS := 'Win':

> dir(`e:/maplev5/update`);

["index.txt", "maple.ind", "maple.lib"]

utils/flines counts lines in a text file.
> fn := `e:/maplev5/etc/latex.txt`:

> flines(fn);
145

utils/fname returns the file name a file descriptor is pointing to.

> fn := open(`e:/maplev5/etc/latex.txt`, READ);
fn := 0
> fname(fn);
"e:/maplev5/etc/latex.txt"

utils/fnumber does the opposite.

Maple system functions:

The utils package features functions to facilitate working with the Maple system in general. They may be helpful for programmers.

utils/addlib adds and utils/dellib deletes paths to/from libname.

> libname;

 e:/maplev5/math, e:/maplev5/utils, c:/maplev4/sgesim,
    c:/maplev4/jsr, c:/maplev4/mv4ext, e:/maplev5/update,
    e:/maplev5/arrayfix, "e:\\maplev5\\lib"

> addlib(`e:/abc`);

 e:/abc, e:/maplev5/math, e:/maplev5/utils, c:/maplev4/sgesim,
    c:/maplev4/jsr, c:/maplev4/mv4ext, e:/maplev5/update,
    e:/maplev5/arrayfix, "e:\\maplev5\\lib"

> dellib(1); # delete first item in libname, here: `e:/abc`.

 e:/maplev5/math, e:/maplev5/utils, c:/maplev4/sgesim,
    c:/maplev4/jsr, c:/maplev4/mv4ext, e:/maplev5/update,
    e:/maplev5/arrayfix, "e:\\maplev5\\lib"

> dellib(-2); # delete second item from the right of libname `e:/maplev5/arrayfix`:

 e:/maplev5/math, e:/maplev5/utils, c:/maplev4/sgesim,
    c:/maplev4/jsr, c:/maplev4/mv4ext, e:/maplev5/update,
    "e:\\maplev5\\lib"

utils/whichlib returns all the Maple libraries a function has been saved to.

> whichlib(maximize);

e:/maplev5/update, "e:\\maplev5\\lib"

utils/li prints the code of a function:

> li(maximize);

proc ()
 local t1;
 option `Copyright (c) 1990 by the University of Waterloo. All rights reserved.`;
 t1 := [minimize(-args[1],args[2 .. nargs])]; op(map(proc (x) options operator, arrow; -x end,t1))
end

utils/load loads functions, Share Library functions, and packages.

> load(iscont, FPS, combinat);

Warning, new definition for Chi
Warning, new definition for cartprod

[FPS, combinat, iscont]

utils/showif prints all interface settings:

> showif();

ansi:          false
autoassign:    R
echo:          1
errorbreak:    1
errorcursor:   true
indentamount:  4
labelling:     true
labelwidth:    20
patchlevel:    1
plotdevice:    inline
plotoptions:   
plotoutput:    terminal
postplot:      []
preplot:       []
prettyprint:   2
prompt:        > 
quiet:         false
screenheight:  25
screenwidth:   79
showassumed:   1
verboseproc:   1
version:       Maple Worksheet Interface, Release 5, IBM INTEL NT, May 11 1998
warnlevel:     3
utils/sysinfo returns various information on the state of the Maple system in a session:
> sysinfo();

             Date:   September 04, 1999 - 17:22:33 (GMT)
          Release:   5.5
           Digits:   10
            Order:   6
        constants:   false   gamma   infinity   true   Catalan   FAIL   Pi   E
          aliases:   I   E
           macros:   bi   eb   ef   inf   lim   new   sc   si   sv
        lasterror:   lasterror
             echo:   1 - echos when input/output is not to/from terminal, no echo with read
      prettyprint:   3 - renders expressions using editable math for output
      verboseproc:   1 - prints the body of user-defined procedures only
        warnlevel:   3 - prints library, kernel, and parser generated warnings
      showassumed:   1 - assumptions are displayed with a trailing tilde
       patchlevel:   1
   assigned names:   186
        currentdir   "e:\\MAPLEV5\\BIN.WNT"
          libname:   e:/maplev5/utils   e:/maplev5/math   c:/maplev4/sgesim
                     c:/maplev4/jsr   c:/maplev4/mks   e:/maplev5/update
                     e:/maplev5/arrayfix   E:\maplev5/update   E:\maplev5/lib
   main Maple lib:   "E:\\maplev5/lib"
        sharename:   not assigned
     Share usable:   false
Share initialized:   no
       open files:   0 = default

utils/vartrack tracks all newly assigned names.

> vartrack('on');

newly assigned variables are now being tracked

> d := 10:

> discont := readlib(discont):

> vartrack();

 [d, discont, discont/IsInteger, discont/IsPositive, discont/NN,
    discont/Z, discont/count, discont/discontR,
    discont/duplicates, discont/zero, int/DefInt]

utils/assumed checks whether an object has assumptions.

> assumed(d);

false

> assume(n, integer);

> assumed(n);

true

utils/prop returns the assumptions (properties) of an onject.

> prop(d);

no property

> prop(n);

integer

utils/leval and utils/neval return information on the evaluation levels of an assigned name. leval returns the values of a name at all evaluation levels, neval returns the number of evaluation levels in a variable.
> s := 1:

> leval(s);
1
> neval(s);
1
> eval(t); # no value assigned to t
t
> leval(t);

> neval(t);
0
> a := b;
a := b
> b :=c;
b := c
> c := x + 1:

> leval(a);
b, c, x + 1
> neval(a);
3
> leval(b);
c, x + 1
> leval(c);
x + 1

utils/remember returns the current contents of the remember table of a function, both built-in and user-defined.

> remember(ln);

[Maple Math]
[Maple Math]
[Maple Math]
[Maple Math]
[Maple Math]
[Maple Math]
[Maple Math]

utils/reinit reinitializes the remember table to a function.
> p := proc(x) x end:

> t := table([1=x]):

> remember(p);
Warning, remember table is empty.
table([
 ])
> p(2) := 'y':

> remember(p);
table([
   2 = y
 ])
> reinit(p);

> remember(p);
Warning, remember table is empty.
table([
 ])
> reinit(p, t);
table([
   1 = x
 ])
> reinit(p, [2='y', 3='z'], 'dummy');
table([
   1 = x
   2 = y
   3 = z
 ])

utils/textfile converts a worksheet that has been stored as a text file by the GUI version of Maple by chosing the menu item file/save as/[Text | Maple text] to a format that is accepted by the read function, removing prompts in Maple input and adding hashes to Maple output and Maple text.

Miscellaneous functions:

Among some other utils functions the following may be interesting. utils/ctime returns the current date and time.

> ctime(CET);

[1998, 10, 20, 20, 32, 47]

utils/date returns date and time as a string. The function accepts most of the place holders known from the bash shell's date command.

> date(EDT, 'dummy'=`%y/%m/%d, %I:%m %p (%Z)`);
99/07/10, 07:07 a.m. (EDT)

utils/man displays R3 TEXT objects in a separate window:

> `help/utils/text/assumed` := TEXT(
> `FUNCTION: utils[assumed] - checks for a name with assumptions`,
> ``,
> `CALLING SEQUENCE:`,
> ` assumed(n);`):

> man(utils, assumed);

utils/Makehelp creates a Release 3 help object from a plain text file and

> whatRelease();

5.5

returns the Maple version.

back

Author: Alexander F. Walz, alexander.f.walz@t-online.de
Original file location: http://www.math.utsa.edu/mirrors/maple/mplutilstour.htm