Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

KDP_book

.pdf
Скачиваний:
5
Добавлен:
03.01.2021
Размер:
2.46 Mб
Скачать

International Academy of Noosphere

the Baltic branch

V.Aladjev, M. Shishakov, V. Vaganov

Mathematica: Functional and

procedural programming

Second edition

KDP Press – 2020

Mathematica: Functional and procedural programming. V. Aladjev, M. Shishakov, V. Vaganov.– KDP Press, 2020.

Software presented in the book contains a number of useful and effective receptions of the procedural and functional programming in Mathematica that extend the system software and allow sometimes much more efficiently and easily to program the software for various purposes. Among them there are means that are of interest from the point of view of including of their or their analogs in Mathematica, at the same time they use approaches, rather useful in programming of various applications. In addition, it must be kept in mind that the classification of the presented tools by their appointment in a certain measure has a rather conditional character because these tools can be crossed substantially among themselves by the functionality.

The freeware package MathToolBox containing more 1420 tools is attached to the present book. The MathToolBox not only contains a number of useful procedures and functions, but can serve as a rather useful collection of programming examples using both standard and nonstandard techniques of functionalprocedural programming.

The book is oriented on a wide enough circle of the users from computer mathematics systems, researchers, teachers and students of universities for courses of computer science, physics, mathematics, and a lot of other natural disciplines. The book will be of interest also to the specialists of industry and technology which use the computer mathematics systems in own professional activity. At last, the book is a rather useful handbook with fruitful methods on the procedural and functional programming in the Mathematica system.

Mathematica 2, 5 ÷ 12.1.1.0 – trademarks of Wolfram Research Inc.

Printed by KDP Press

December, 2020

© <2020> by V. Aladjev, M. Shishakov, V. Vaganov

Mathematica: Functional and procedural programming

Contents

Introduction

5

Chapter 1: The user functions in Mathematica

7

1.1. The user functions, defined intuitively

8

1.2. The user pure functions

12

1.3. Some useful tools for work with the user functions

20

Chapter 2: The user procedures in Mathematica

28

2.1. Definition of procedures in Mathematica software

29

2.2. Headings of procedures

38

2.3. Optional arguments of procedures and functions

57

2.4. Local variables in Mathematica procedures

71

2.5. Exit mechanisms of the user procedures

86

2.6. Tools for testing of procedures and functions

94

2.7. The nested blocks and modules

102

Chapter 3: Programming tools of the user procedure body

107

3.1. Branching control structures in the Mathematica

111

* Conditional branching structures

111

* Unconditional transitions

115

3.2. Cyclic control structures in the Mathematica

120

3.3. Some special types of cyclic control structures in

 

the Mathematica system

125

3.4. Mathematica tools for string expressions

130

* Replacements and extractions in strings

141

* Sub-strings processing in strings

143

* Expressions containing in strings

155

3.5. Mathematica tools for lists processing

160

3.6. Additional tools for the Mathematica

197

3.7. Attributes of procedures and functions

248

3.8. Additional tools expanding the built-in

 

Mathematica functions, or its software as a whole

254

3.9. Certain additional tools of expressions processing

 

in the Mathematica software

272

* Tools of testing of correctness of expressions

273

* Expressions processing at level of their components

277

 

 

3

 

V.Z. Aladjev, M.L. Shishakov, V.A. Vaganov

* Replacement sub-expressions in expressions

285

* Expressions in strings

297

Chapter 4: Software for input-output in Mathematica

300

4.1. Tools of Mathematica for work with internal files

300

4.2. Tools of Mathematica for work with external files

305

4.3. Tools of Mathematica for attributes processing of

 

directories and data files

316

4.4. Additional tools for files and directories processing

 

of file system of the computer

323

4.5. Special tools for files and directories processing

333

Chapter 5: Organization of the user software

341

5.1. MathToolBox package for Mathematica system

345

5.2. Operating with the user packages in Mathematica

354

* The concept of context in Mathematica

355

* Interconnection of contexts and packages

363

5.3. Additional tools of operating with user packages

377

References

391

About the authors

395

Book completes our multiyear cycle of book publications on general theory of statistics, computer science, cellular automata, Mathematica and Maple, with creation of software for the latest two computer mathematics systems Maple and Mathematica [42] and [16] accordingly.

All rights reserved. This book or any portion thereof may not be reproduced or used in any manner whatsoever without the express written permission of the publisher except for the use of brief quotations in a book review or a scholarly journal. This book completes a multi-year cycle of our publications in five areas: General theory of statistics, Information science, Cellular automata, Maple and Mathematica along with creation of software for Maple and Mathematica.

The authors express deep gratitude and appreciation to Misters Uwe Teubel and Dmitry Vassiliev – the representatives of the firms

REAG Renewable Energy AG & Purwatt AG (Switzerland) for essential assistance rendered by preparation of the present book.

For contacts: aladjev@europe.com, aladjev@yandex.ru, aladjev@mail.ru

4

Mathematica: Functional and procedural programming

Introduction

Systems of computer mathematics (SCM) find wide enough application in a whole number of natural, economic and social sciences such as: technologies, chemistry, informatics, mathematics, physics, education, economics, sociology, etc. Systems Mathematica and Maple, and some others are more and more demanded for learning of mathematically oriented disciplines, in scientifical researches and technologies. SCM are main tools for scientists, teachers, researchers, and engineers. The investigations on the basis of SCM, as a rule, well combine algebraical methods with advanced computing methods. In this sense, SCM are a certain interdisciplinary area between informatics and mathematics in which researches will be concentrated on the development of algorithms for algebraic (symbolical) and numerical calculations, data processing, and development of programming languages along with software for realization of algorithms of this kind and problems of different purpose basing on them.

It is possible to note that among modern SCM the leading positions are undoubtedly taken by the Maple and Matematica systems, alternately being ahead of each other on this or that indicator. The given statement is based on our longterm use in different purposes of both systems – Maple and Mathematica and also work on preparation and edition of the book series and some papers in Russian and English in this direction [1-42]. At the same time, as a result of expanded use of the above systems were created the package MathToolBox for Mathematica and library UserLib6789 for Maple [16,42]. All tools from the above library and package are supplied with freeware license and have open program code. Programming of many projects in Maple and Mathematica substantially promoted emergence of a lot of system tools from the above library and package. So, openness of MathToolBox package code allows both to modify the tools containing in it, and to program on their basis own tools, or to use their components in various appendices. Experience of use of library and package showed efficiency of such approach.

5

V.Z. Aladjev, M.L. Shishakov, V.A. Vaganov

In particular, MathToolBox package contains more than 1420 tools of different purpose which eliminate restrictions of a number of standard tools of Mathematica system, and expand its software with new tools. In this context, this package can serve as a certain additional tool of procedural and functional programming, especially useful in the numerous appendices where certain nonstandard evaluations have to accompany programming. At that, tools represented in this package have a direct relationship to certain principal questions of procedural and functional programming in Mathematica system, not only for the decision of applied problems, but, above all, for creation of software extending frequently used facilities of the system, eliminating their defects or extending Mathematica with new facilities. The software presented in the package contains a lot of rather useful and effective receptions of programming in the Mathematica, and extends its software that allows to program the tasks of various purpose more simply and more effectively. A number of tools of the given package is used in the examples illustrating these or those provisions of the book.

In the book basic objects of programming in Mathematica – functions and procedures are considered that consist the base of functionalprocedural programming. The given book considers some principal questions of proceduralfunctional programming in Mathematica, not only for decision of various applied tasks, but, as well, for creation of software expanding frequently used facilities of the system and/or eliminating their limitations, or expanding the system with new facilities. The important role of functions and procedures take place at creation of effective and intelligible user software in various fields. This also applies to software reliability.

The book is oriented on a wide enough circle of the users of the CMS, researchers, mathematicians, physicists, teachers and students of universities for courses of mathematics, computer science, physics, chemistry, etc. The book will be of interest to the specialists of industry and technology, economics, medicine and others too, that use the CMS in own professional activity.

6

Mathematica: Functional and procedural programming

Chapter 1: The user functions in Mathematica

Function is one of basic concepts of mathematics, being not less important object in programming systems, not excluding Mathematica system, with that difference that function as a subject to programming very significantly differs from strictly mathematical concept of function, considering specific features of programming in the Mathematica system.

Mathematica has a large number of functions of different purpose and operations over them. Each function is rather well documented and supplied with the most typical examples of its application. Unfortunately, unlike Maple, the program code of the Mathematica functions is closed that significantly narrows a possibility of deeper mastering the system and acquaintance with the receptions used by it and a technique of programming.

Truth, with rare exception, Mathematica allows to make assignments that override the standard builtin functions and meaning of Mathematica objects. However, program codes of the builtin functions of the system remain closed for the user. Names of builtin functions submit to some general properties, namely: names consist of complete English words, or standard mathematical abbreviations. In addition, the first letter of each name is capitalized. Functions whose names end with Q letter as a rule usually "ask a question", and return either True or False.

Many important functions of the Mathematica system can be found in our books [1-15], that provide detailed discussions of the built-in functions, the features of their implementation along with our tools [16] which expand or supplement them. A full arsenal of functionality can be found in the system manual. Here we will cover the basic issues of organizing user functions in Mathematica along with some tools that provide a number of important operations over user-defined functions. Moreover, it is possible to get acquainted with many of them in package MathToolBox [16] and in certain our books [1-15]. We pass to definition of the main functional user objects.

7

V.Z. Aladjev, M.L. Shishakov, V.A. Vaganov

1.1. The classical functions, defined intuitively. Functions of this type are determines by expressions as follows:

(a)F[x_, y_, z_, …] := [x, y, z, …]

(b)F[x_ /; TestQ[x], y_, z_ /; TestQ[z], ] := [x, y, z, …]

Definition allows two formats (a) and (b) from which the first format is similar to the format of a classical mathematical function f(x, y, z, ...) = (x, y, z, ...) from n variables with that difference that for formal arguments x,y,z,... the object template are used _which can designate any admissible expression of the system while (x,y,z,…) designate an arbitrary expression from variables x,y,z ..., including constants and function calls, for example:

In[1425]:= F[x_, y_, z_] := a*x*b*y + N[Sin[2020]] In[1426]:= F[42, 78, 2020]

Out[1426]= 0.044062 + 3276*a*b

Whereas the second format unlike the first allows to hold testing of actual arguments obtained at function call F[x, y, z] for validity. It does a testing expression TestQ[x] attributed to formal argument e.g. x – if at least one testing expression on a relevant argument returns False, then function call is returned unevaluated, otherwise the function call returns the required value, if at evaluation of expression was no an erroneous or especial situation, for example:

In[8]:= F[x_ /; IntegerQ[x], y_, z_Symbol] := a*x*b*y + c*z In[9]:= F[77, 90, G]

Out[9]= 6930*a*b + c*G In[10]:= F[77, 90, 78]

Out[10]= F[77, 90, 78]

At the same time, for an actual argument its Head, e.g. List, Integer, String, Symbol, etc, as that illustrates the above example, can act as a test. At standard approach the concept of a function does not allow the use of local variables. As a rule Mathematica system assumes that all variables are global. This means that every time you use a name e.g. w, the Mathematica normally assumes that you are referring to the same object. However, at

8

Mathematica: Functional and procedural programming

program writing, you may not want all variables to be global. In this case, you need the w in different points of a program to be treated as a local variable. At the same time, local variables in function definition can be set using modules. Within module you can give a list of variables which are to be treated as local. This goal can be achieved with help of blocks too. A simple example illustrates the told:

In[47]:= F[x_, y_] := x*y + Module[{a = 5, b = 6}, a*x + b*y] In[48]:= F[42, 78]

Out[48]= 3954 In[49]:= {a, b} = {0, 0} Out[49]= {0, 0} In[50]:= F[42, 78]

Out[50]= 3954

In[51]:= S[x_, y_] := x*Block[{a = 5, b = 6}, a/b*y^2] In[52]:= S[42, 48]

Out[52]= 80640

In[53]:= {a, b} = {0, 0}; S[42, 48]

Out[53]= 80640

In addition, pattern object "___" or "__" is used for formal arguments in a function definition can stand for any sequence of zero or more expressions or for any nonempty sequence of expressions accordingly, for example:

In[2257]:= G[x__] := Plus[x]

In[2258]:= G[500, 90, 46]

Out[2258]= 636

In[2259]:= G1[x___] := Plus[x]

In[2260]:= {G1[], G1[42, 47, 67]}

Out[2260]= {0, 156}

Lack of such definition of function is that the user cannot use local variables, for example, the coefficients of polynomials and other symbols other than calls of standard functions or local symbols determined by the artificial reception described above

(otherwise function will depend on their current values in the current session with Mathematica system). So, at such function definition

9

V.Z. Aladjev, M.L. Shishakov, V.A. Vaganov

expression should depend only on formal arguments. But in a number of cases it is quite enough. This function definition is used to give a more complete view of this object and in certain practical cases it is indeed used [9-12,16].

Meanwhile, using our procedure [16] with program code:

In[2274]:= Sequences[x__] := Module[{a = Flatten[{x}], b},

b = "Sequence[" <> ToString1[a] <> "]"; a = Flatten[StringPosition[b, {"{", "}"}]]; ToExpression[StringReplace[b, {StringTake[b, {a[[1]], a[[1]]}] > "", StringTake[b, {a[[1]], a[[1]]}] > ""}]]]

that extends the standard built-in Sequence function and useful in many applications, it is possible to represent another way to define the user functions, modules, and blocks, more precisely their headers based on constructions of the format:

<Function name>@Sequences[formal args] :=

The following a rather simple example illustrates the told:

In[75]:= G@Sequences[a_Integer, b_Symbol, c_] := a+b+c In[76]:= Definition[G]

Out[76]= G[a_Integer, b_Symbol, c_] := a + b + c In[77]:= G[6.7, 5, 7]

Out[77]= G[6.7, 5, 7] In[78]:= G[67, m, 7]

Out[78]= 74 + m

Naturally, in real programming, this definition of functions is not practical, serving only the purposes of possible methods of defining said objects. In the meantime, such extension of the built-in tool allows comparing the capabilities of both tools in determining the underlying objects of the system.

Along with the above types of functions, the Mathematica uses also the Compile function intended for compilation of the functions which calculate numeric expressions at quite certain assumptions. The Compile function has the 4 formats of coding, each of which is oriented on a certain compilation type:

Compile[{x1, x2,…}, G] compiles a function for calculation of an expression G in the assumption that all values of arguments xj {j =

10

Тут вы можете оставить комментарий к выбранному абзацу или сообщить об ошибке.

Оставленные комментарии видны всем.

Соседние файлы в предмете Математические пакеты