-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy path1-Manual.mdoc
1374 lines (1007 loc) · 47.9 KB
/
1-Manual.mdoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<chapter title="Introduction">
\Mathics---to be pronounced like "Mathematics" without the "emat"---is a general-purpose computer algebra system (CAS). It is meant to be a free, open-source alternative to \Mathematica. It is free both as in "free beer" and as in "freedom". Mathics can be run \Mathics locally, and to facilitate installation of the vast amount of software need to run this, there is a <url>:docker image available on dockerhub: https://hub.docker.com/r/mathicsorg/mathics</url>.
The programming language of \Mathics is meant to resemble the \Wolfram Language as much as possible. However, \Mathics is in no way affiliated or supported by \Wolfram. \Mathics will probably never have the power to compete with \Mathematica in industrial applications; it is an alternative though. It also invites community development at all levels.
See the <url>:installation instructions: https://mathics-development-guide.readthedocs.io/en/latest/installing/index.html</url> for the most recent instructions for installing from PyPI, or the source.
For implementation details see <url>https://mathics-development-guide.readthedocs.io/en/latest/</url>.
<section title="Why yet another CAS, one based on Mathematica?">
\Mathematica is great, but it a couple of disadvantages.
<ul>
<li>It is not open source.
<li>Its development is tightly controlled and centralized, and as such
<li>it can't hook into different kinds open-source packages that have independently developed algorithms and methods
</ul>
The second point some may find and advantage.
However, even if you are willing to pay hundreds of dollars for the software, you would will not be able to see what\'s going on "inside" the program if that is your interest. That\'s what free, open-source, and community-supported software is for!
\Mathics aims at combining the best of both worlds: the beauty of \Mathematica backed by a free, extensible Python core which includes a rich set of Python tools including:
<ul>
<li><url>:mpmath: https://mpmath.org/</url> for floating-point arithmetic with arbitrary precision,
<li><url>:numpy: https://numpy.org/numpy</url> for numeric computation,
<li><url>:SymPy: https://sympy.org</url> for symbolic mathematics, and
<li>optionally <url>:SciPy: https://www.scipy.org/</url> for Scientific calculations.
</ul>
Performance of \Mathics is not, right now, practical in large-scale projects and calculations. However can be used as a tool for exploration and education.
</section>
<section title="What does \Mathics offer?">
Some of the features of \Mathics tries to be compatible with Wolfram-Language kernel within the confines of the Python ecosystem.
Given this, it is a powerful functional programming language, driven by pattern matching and rule application.
Primitive types include rationals, complex numbers, and arbitrary-precision numbers. Other primitive types such as images or graphs, or NLP come from the various Python libraries that \Mathics uses.
Outside of the "core" \Mathics kernel (which has a only primitive command-line interface), in separate github projects, as add-ons, there is:
<ul>
<li>a Django-based web server
<li>a command-line interface using either prompt-toolkit, or GNU Readline
<li>a <url>:Mathics3 module for Graphs:https://pypi.org/project/pymathics-graph/</url> (via <url>:NetworkX:https://networkx.org/</url>),
<li>a <url>:Mathics3 module for NLP:https://pypi.org/project/pymathics-natlang/</url> (via <url>:nltk:https://www.nltk.org/</url>, <url>:spacy:https://spacy.io/</url>, and others)
<li>a <url>:A docker container:https://hub.docker.com/r/mathicsorg/mathics</url> which bundles all of the above
</ul>
</section>
<section title="History">
The first alpha versions of \Mathics were done in 2011 by Jan Pöschko. He worked on it for a couple of years to about the v0.5 release in 2012. By then, it had 386 built-in symbols. Currently there are over a 1,000 and even more when \Mathics modules are included.
After that, Angus Griffith took over primary leadership and rewrote the parser to pretty much the stage it is in now. He and later Ben Jones worked on it from 2013 to about 2017 to the v1.0 release. Towards the end of this period, Bernhard Liebl worked on this, mostly focused on graphics.
A <url>:docker image of the v.9 release: https://hub.docker.com/r/arkadi/mathics</url> can be found on dockerhub.
Around 2017, the project was largely abandoned in its largely Python 2.7 state, with support for Python 3.2-3.5 via six.
Subsequently, around mid 2020, it was picked up by the current developers. A list of authors and contributors can be found in the <url>
:<con>AUTHORS.txt</con>:
https://github.com/Mathics3/mathics-core/blob/master/AUTHORS.txt</url> file.
</section>
<section title="What is missing?">
There are lots of ways in which \Mathics could still be improved. <url>:<con>FUTURE.rst</con>: https://github.com/Mathics-3/mathics/blob/master/FUTURE.txt</url> has the current roadmap.
While we always could use help, such as in Python programming, improving Documentation. But there are other ways to help. For example:
<ul>
<li>Ensure this document is complete and accurate. We could use help to ensure all of the Builtin functions described properly and fully, and that they have link to corresponding Wiki, Sympy, WMA and/or mpath links.
Make sure the builtin summaries and examples clear and useful.</li>
<li>We could use help in LaTeX styling, and going over this document to remove overful boxes and things of that nature. We could also use help and our use of Asymptote. The are some graphics primitives such as for polyhedra that haven't been implemented. Similar graphics options are sometimes missing in Asymptote that we have available in other graphics backends.</li>
<li>add another graphics backend: it could be a javascript library like jsfiddle</li>
<li>Consider donating via <url>:Github Sponsors: https://github.com/sponsors</url> or some other mechanism.</li>
</ul>
</section>
See <url>:The Mathics3 Developer Guide:https://mathics-development-guide.readthedocs.io/en/latest/</url> for how to get started using and developing \Mathics.
</chapter>
<chapter title="Language Tutorial">
The following sections are introductions to the basic principles of the language of \Mathics. A few examples and functions are presented. Only their most common usages are listed; for a full description of a Symbols possible arguments, options, etc., see its entry in the Reference of Built-in Symbols.
However if you google for "Mathematica Tutorials" you will find easily dozens of other tutorials which are applicable. Be warned though that \Mathics does not yet offer the full range and features and capabilities of \Mathematica.
<section title="Basic calculations">
\Mathics can be used to calculate basic stuff:
>> 1 + 2
= 3
To submit a command to \Mathics, press 'Shift+Return' in the Web interface or 'Return' in the console interface. The result will be printed in a new line below your query.
\Mathics understands all basic arithmetic operators and applies the usual operator precedence. Use parentheses when needed:
>> 1 - 2 * (3 + 5) / 4
= -3
The multiplication can be omitted:
>> 1 - 2 (3 + 5) / 4
= -3
>> 2 4
= 8
Powers can be entered using '^':
>> 3 ^ 4
= 81
Integer divisions yield rational numbers:
>> 6 / 4
= 3 / 2
To convert the result to a floating point number, apply the function 'N':
>> N[6 / 4]
= 1.5
As you can see, functions are applied using square braces '[' and ']', in contrast to the common notation of '(' and ')'. At first hand, this might seem strange, but this distinction between function application and precedence change is necessary to allow some general syntax structures, as you will see later.
\Mathics provides many common mathematical functions and constants, e.g.:
>> Log[E]
= 1
>> Sin[Pi]
= 0
>> Cos[0.5]
= 0.877583
When entering floating point numbers in your query, \Mathics will perform a numerical evaluation and present a numerical result, pretty much like if you had applied 'N'.
Of course, \Mathics has complex numbers:
>> Sqrt[-4]
= 2 I
>> I ^ 2
= -1
>> (3 + 2 I) ^ 4
= -119 + 120 I
>> (3 + 2 I) ^ (2.5 - I)
= 43.663 + 8.28556 I
>> Tan[I + 0.5]
= 0.195577 + 0.842966 I
'Abs' calculates absolute values:
>> Abs[-3]
= 3
>> Abs[3 + 4 I]
= 5
\Mathics can operate with pretty huge numbers:
>> 100!
= 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
('!' denotes the factorial function.)
The precision of numerical evaluation can be set:
>> N[Pi, 30]
= 3.14159265358979323846264338328
Division by zero is forbidden:
>> 1 / 0
: Infinite expression 1 / 0 encountered.
= ComplexInfinity
Other expressions involving 'Infinity' are evaluated:
>> Infinity + 2 Infinity
= Infinity
In contrast to combinatorial belief, '0^0' is undefined:
>> 0 ^ 0
: Indeterminate expression 0 ^ 0 encountered.
= Indeterminate
The result of the previous query to \Mathics can be accessed by '%':
>> 3 + 4
= 7
>> % ^ 2
= 49
##
</section>
<section title="Precision and Accuracy">
\Mathics handles relative and absolute uncertanties in numerical quantities. The <em>precision</em> or relative accuracy, is set by adding a RawBackquote character ('`') and the number of digits of precision in the mantissa. For example:
>> 3.1416`3
= 3.14
Above, two decimal places are shown in output after the decimal point, but three places of precision are stored.
The relative uncertainty of '3.1416`3' is 10^-3. It is numerically equivalent, in three places after the decimal point, to 3.1413`4:
>> 3.1416`3 == 3.1413`4
= True
We can get the precision of the number by using the \Mathics Built-in function <url>:'Precision': /doc/reference-of-built-in-symbols/atomic-elements-of-expressions/representation-of-numbers/precision/</url>:
>> Precision[3.1413`4]
= 4.
While 3.1419 not the closest approximation to Pi in 4 digits after the decimal point (or with precision 4), for 3 digits of precision it is:
>> Pi == 3.141987654321`3
= True
<url>The absolute accuracy of a number, is set by adding a two RawBackquotes '``' and the number digits.
For example:
>> 13.1416``4
= 13.142
is a number having a absolute uncertainty of 10^-4. This number is numerically equivalent to '13.1413``4':
>> 13.1416``4 == 13.1413``4
= True
The absolute accuracy for the value 0 is a fixed-precision Real number:
>> 0``4
= 0.0000
See also <url>:Accuracy and precision: https://en.wikipedia.org/wiki/Accuracy_and_precision</url>.
</section>
<section title="Symbols and Assignments">
Symbols need not be declared in \Mathics, they can just be entered and remain variable:
>> x
= x
Basic simplifications are performed:
>> x + 2 x
= 3 x
Symbols can have any name that consists of characters and digits:
>> iAm1Symbol ^ 2
= iAm1Symbol ^ 2
You can assign values to symbols:
>> a = 2
= 2
>> a ^ 3
= 8
>> a = 4
= 4
>> a ^ 3
= 64
Assigning a value returns that value. If you want to suppress the output of any result, add a ';' to the end of your query:
>> a = 4;
Values can be copied from one variable to another:
>> b = a;
Now changing 'a' does not affect 'b':
>> a = 3;
>> b
= 4
Such a dependency can be achieved by using "delayed assignment" with the ':=' operator (which does not return anything, as the right side is not even evaluated):
>> b := a ^ 2
>> b
= 9
>> a = 5;
>> b
= 25
##
</section>
<section title="Comparisons and Boolean Logic">
Values can be compared for equality using the operator '==':
>> 3 == 3
= True
>> 3 == 4
= False
The special symbols 'True' and 'False' are used to denote truth values. Naturally, there are inequality comparisons as well:
>> 3 > 4
= False
Inequalities can be chained:
>> 3 < 4 >= 2 != 1
= True
Truth values can be negated using '!' (logical <em>not</em>) and combined using '&&' (logical <em>and</em>) and '||' (logical <em>or</em>):
>> !True
= False
>> !False
= True
>> 3 < 4 && 6 > 5
= True
'&&' has higher precedence than '||', i.e. it binds stronger:
>> True && True || False && False
= True
>> True && (True || False) && False
= False
##
</section>
<section title="Strings">
Strings can be entered with '"' as delimiters:
>> "Hello world!"
= Hello world!
As you can see, quotation marks are not printed in the output by default. This can be changed by using 'InputForm':
>> InputForm["Hello world!"]
= "Hello world!"
Strings can be joined using '<>':
>> "Hello" <> " " <> "world!"
= Hello world!
Numbers cannot be joined to strings:
>> "Debian" <> 6
: String expected.
= Debian <> 6
They have to be converted to strings using 'ToString' first:
>> "Debian" <> ToString[6]
= Debian6
##
</section>
<section title="Working with Lists">
Lists can be entered in \Mathics with curly braces '{' and '}':
>> mylist = {a, b, c, d}
= {a, b, c, d}
There are various functions for constructing lists:
>> Range[5]
= {1, 2, 3, 4, 5}
>> Array[f, 4]
= {f[1], f[2], f[3], f[4]}
>> ConstantArray[x, 4]
= {x, x, x, x}
>> Table[n ^ 2, {n, 2, 5}]
= {4, 9, 16, 25}
The number of elements of a list can be determined with 'Length':
>> Length[mylist]
= 4
Elements can be extracted using double square braces:
>> mylist[[3]]
= c
Negative indices count from the end:
>> mylist[[-3]]
= b
Lists can be nested:
>> mymatrix = {{1, 2}, {3, 4}, {5, 6}};
There are alternate forms to display lists:
>> TableForm[mymatrix]
= 1 2
.
. 3 4
.
. 5 6
>> MatrixForm[mymatrix]
= 1 2
.
. 3 4
.
. 5 6
There are various ways of extracting elements from a list:
>> mymatrix[[2, 1]]
= 3
>> mymatrix[[;;, 2]]
= {2, 4, 6}
>> Take[mylist, 3]
= {a, b, c}
>> Take[mylist, -2]
= {c, d}
>> Drop[mylist, 2]
= {c, d}
>> First[mymatrix]
= {1, 2}
>> Last[mylist]
= d
>> Most[mylist]
= {a, b, c}
>> Rest[mylist]
= {b, c, d}
Lists can be used to assign values to multiple variables at once:
>> {a, b} = {1, 2};
>> a
= 1
>> b
= 2
Operations like addition and multiplication, "thread" over lists; lists are combined element-wise:
>> {1, 2, 3} + {4, 5, 6}
= {5, 7, 9}
>> {1, 2, 3} * {4, 5, 6}
= {4, 10, 18}
It is an error to combine lists with unequal lengths:
>> {1, 2} + {4, 5, 6}
: Objects of unequal length cannot be combined.
= {1, 2} + {4, 5, 6}
##
</section>
<section title="The Structure of \Mathics Objects">
Every expression in \Mathics is built upon the same principle: it consists of a <em>head</em> and an arbitrary number of <em>children</em>, unless it is an <em>atom</em>, i.e. it can not be subdivided any further. To put it another way: everything is a function call. This can be best seen when displaying expressions in their "full form":
>> FullForm[a + b + c]
= Plus[a, b, c]
Nested calculations are nested function calls:
>> FullForm[a + b * (c + d)]
= Plus[a, Times[b, Plus[c, d]]]
Even lists are function calls of the function 'List':
>> Head[{1, 2, 3}]
= List
However, its full form is presented with ${\ldots}$
>> FullForm[{1, 2, 3}]
= {1,2,3}
The head of an expression can be determined with 'Head':
>> Head[a + b + c]
= Plus
The children of an expression can be accessed like list elements:
>> (a + b + c)[[2]]
= b
The head is the 0th element:
>> (a + b + c)[[0]]
= Plus
The head of an expression can be exchanged using the function 'Apply':
>> Apply[g, f[x, y]]
= g[x, y]
>> Apply[Plus, a * b * c]
= a + b + c
'Apply' can be written using the operator '@@':
>> Times @@ {1, 2, 3, 4}
= 24
(This exchanges the head 'List' of '{1, 2, 3, 4}' with 'Times', and then the expression 'Times[1, 2, 3, 4]' is evaluated, yielding 24.)
'Apply' can also be applied on a certain <em>level</em> of an expression:
>> Apply[f, {{1, 2}, {3, 4}}, {1}]
= {f[1, 2], f[3, 4]}
Or even on a range of levels:
>> Apply[f, {{1, 2}, {3, 4}}, {0, 2}]
= f[f[1, 2], f[3, 4]]
'Apply' is similar to 'Map' ('/@'):
>> Map[f, {1, 2, 3, 4}]
= {f[1], f[2], f[3], f[4]}
>> f /@ {{1, 2}, {3, 4}}
= {f[{1, 2}], f[{3, 4}]}
The atoms of \Mathics are numbers, symbols, and strings. 'AtomQ' tests whether an expression is an atom:
>> AtomQ[5]
= True
>> AtomQ[a + b]
= False
The full form of rational and complex numbers looks like they were compound expressions:
>> FullForm[3 / 5]
= Rational[3, 5]
>> FullForm[3 + 4 I]
= Complex[3, 4]
However, they are still atoms, thus unaffected by applying functions, for instance:
>> f @@ Complex[3, 4]
= 3 + 4 I
Nevertheless, every atom has a head:
>> Head /@ {1, 1/2, 2.0, I, "a string", x}
= {Integer, Rational, Real, Complex, String, Symbol}
The operator '===' tests whether two expressions are the same on a structural level:
>> 3 === 3
= True
>> 3 == 3.0
= True
But:
>> 3 === 3.0
= False
because '3' (an 'Integer') and '3.0' (a 'Real') are structurally different.
##
</section>
<section title="Functions and Patterns">
Functions can be defined in the following way:
>> f[x_] := x ^ 2
This tells \Mathics to replace every occurrence of 'f' with one (arbitrary) parameter 'x' with 'x ^ 2'.
>> f[3]
= 9
>> f[a]
= a ^ 2
The definition of 'f' does not specify anything for two parameters, so any such call will stay unevaluated:
>> f[1, 2]
= f[1, 2]
In fact, <em>functions</em> in \Mathics are just one aspect of <em>patterns</em>: 'f[x_]' is a pattern that <em>matches</em> expressions like 'f[3]' and 'f[a]'. The following patterns are available:
<dl>
<dt>'_' or 'Blank[]'
<dd>matches one expression.
<dt>'Pattern[$x$, $p$]'
<dd>matches the pattern $p$ and stores the value in $x$.
<dt>'$x$_' or 'Pattern[$x$, Blank[]]'
<dd>matches one expression and stores it in $x$.
<dt>'__' or 'BlankSequence[]'
<dd>matches a sequence of one or more expressions.
<dt>'___' or 'BlankNullSequence[]'
<dd>matches a sequence of zero or more expressions.
<dt>'_$h$' or 'Blank[$h$]'
<dd>matches one expression with head $h$.
<dt>'$x$_$h$' or 'Pattern[$x$, Blank[$h$]]'
<dd>matches one expression with head $h$ and stores it in $x$.
<dt>'$p$ | $q$' or 'Alternatives[$p$, $q$]'
<dd>matches either pattern $p$ or $q$.
<dt>'$p$ ? $t$' or 'PatternTest[$p$, $t$]'
<dd>matches $p$ if the test '$t$[$p$]' yields 'True'.
<dt>'$p$ /; $c$' or 'Condition[$p$, $c$]'
<dd>matches $p$ if condition $c$ holds.
<dt>'Verbatim[$p$]'
<dd>matches an expression that equals $p$, without regarding patterns inside $p$.
</dl>
As before, patterns can be used to define functions:
>> g[s___] := Plus[s] ^ 2
>> g[1, 2, 3]
= 36
'MatchQ[$e$, $p$]' tests whether $e$ matches $p$:
>> MatchQ[a + b, x_ + y_]
= True
>> MatchQ[6, _Integer]
= True
'ReplaceAll' ('/.') replaces all occurrences of a pattern in an expression using a 'Rule' given by '->':
>> {2, "a", 3, 2.5, "b", c} /. x_Integer -> x ^ 2
= {4, a, 9, 2.5, b, c}
You can also specify a list of rules:
>> {2, "a", 3, 2.5, "b", c} /. {x_Integer -> x ^ 2.0, y_String -> 10}
= {4., 10, 9., 2.5, 10, c}
'ReplaceRepeated' ('//.') applies a set of rules repeatedly, until the expression doesn\'t change anymore:
>> {2, "a", 3, 2.5, "b", c} //. {x_Integer -> x ^ 2.0, y_String -> 10}
= {4., 100., 9., 2.5, 100., c}
There is a "delayed" version of 'Rule' which can be specified by ':>' (similar to the relation of ':=' to '='):
>> a :> 1 + 2
= a :> 1 + 2
>> a -> 1 + 2
= a -> 3
This is useful when the right side of a rule should not be evaluated immediately (before matching):
>> {1, 2} /. x_Integer -> N[x]
= {1, 2}
Here, 'N' is applied to 'x' before the actual matching, simply yielding 'x'. With a delayed rule this can be avoided:
>> {1, 2} /. x_Integer :> N[x]
= {1., 2.}
'ReplaceAll' and 'ReplaceRepeated' take the first possible match.
However 'ReplaceList' returns a list of all possible matches.
This can be used to get all subsequences of a list, for instance:
>> ReplaceList[{a, b, c}, {___, x__, ___} -> {x}]
= {{a}, {a, b}, {a, b, c}, {b}, {b, c}, {c}}
'ReplaceAll' would just return the first expression:
>> ReplaceAll[{a, b, c}, {___, x__, ___} -> {x}]
= {a}
In addition to defining functions as rules for certain patterns, there are <em>pure</em> functions that can be defined using the '&' postfix operator, where everything before it is treated as the function body and '#' can be used as argument placeholder:
>> h = # ^ 2 &;
>> h[3]
= 9
Multiple arguments can simply be indexed:
>> sum = #1 + #2 &;
>> sum[4, 6]
= 10
It is also possible to name arguments using 'Function':
>> prod = Function[{x, y}, x * y];
>> prod[4, 6]
= 24
Pure functions are very handy when functions are used only locally, e.g., when combined with operators like 'Map':
>> # ^ 2 & /@ Range[5]
= {1, 4, 9, 16, 25}
Sort according to the second part of a list:
>> Sort[{{x, 10}, {y, 2}, {z, 5}}, #1[[2]] < #2[[2]] &]
= {{y, 2}, {z, 5}, {x, 10}}
Functions can be applied using prefix or postfix notation, in addition to using '[]':
>> h @ 3
= 9
>> 3 // h
= 9
##
</section>
<section title="Program-Flow Control Statements">
Like most programming languages, \Mathics has common program-flow control statements for conditions, loops, etc.:
<dl>
<dt>'If[$cond$, $pos$, $neg$]'
<dd>returns $pos$ if $cond$ evaluates to 'True', and $neg$ if it evaluates to 'False'.
<dt>'Which[$cond1$, $expr1$, $cond2$, $expr2$, ...]'
<dd>yields $expr1$ if $cond1$ evaluates to 'True', $expr2$ if $cond2$ evaluates to 'True', etc.
<dt>'Do[$expr$, {$i$, $max$}]'
<dd>evaluates $expr$ $max$ times, substituting $i$ in $expr$ with values from 1 to $max$.
<dt>'For[$start$, $test$, $incr$, $body$]'
<dd>evaluates $start$, and then iteratively $body$ and $incr$ as long as $test$ evaluates to 'True'.
<dt>'While[$test$, $body$]'
<dd>evaluates $body$ as long as $test$ evaluates to 'True'.
<dt>'Nest[$f$, $expr$, $n$]'
<dd>returns an expression with $f$ applied $n$ times to $expr$.
<dt>'NestWhile[$f$, $expr$, $test$]'
<dd>applies a function $f$ repeatedly on an expression $expr$, until
applying $test$ on the result no longer yields 'True'.
<dt>'FixedPoint[$f$, $expr$]'
<dd>starting with $expr$, repeatedly applies $f$ until the result no longer changes.
</dl>
>> If[2 < 3, a, b]
= a
>> x = 3; Which[x < 2, a, x > 4, b, x < 5, c]
= c
Compound statements can be entered with ';'. The result of a compound expression is its last part or 'Null' if it ends with a ';'.
>> 1; 2; 3
= 3
>> 1; 2; 3;
Inside 'For', 'While', and 'Do' loops, 'Break[]' exits the loop and 'Continue[]' continues to the next iteration.
>> For[i = 1, i <= 5, i++, If[i == 4, Break[]]; Print[i]]
| 1
| 2
| 3
##
</section>
<section title="Scoping">
By default, all symbols are "global" in \Mathics, i.e. they can be read and written in any part of your program.
However, sometimes "local" variables are needed in order not to disturb the global namespace. \Mathics provides two ways to support this:
<ul>
<li><em>lexical scoping</em> by 'Module', and
<li><em>dynamic scoping</em> by 'Block'.
</ul>
<dl>
<dt>'Module[{$vars$}, $expr$]'
<dd>localizes variables by giving them a temporary name of the form
'name$number', where number is the current value of '$ModuleNumber'. Each time a module
is evaluated, '$ModuleNumber' is incremented.
<dt>'Block[{$vars$}, $expr$]'
<dd>temporarily stores the definitions of certain variables, evaluates
$expr$ with reset values and restores the original definitions afterwards.
</dl>
Both scoping constructs shield inner variables from affecting outer ones:
>> t = 3;
>> Module[{t}, t = 2]
= 2
>> Block[{t}, t = 2]
= 2
>> t
= 3
'Module' creates new variables:
>> y = x ^ 3;
>> Module[{x = 2}, x * y]
= 2 x ^ 3
'Block' does not:
>> Block[{x = 2}, x * y]
= 16
Thus, 'Block' can be used to temporarily assign a value to a variable:
>> expr = x ^ 2 + x;
>> Block[{x = 3}, expr]
= 12
>> x
= x
'Block' can also be used to temporarily change the value of system parameters:
>> Block[{$RecursionLimit = 30}, x = 2 x]
: Recursion depth of 30 exceeded.
= $Aborted
>> f[x_] := f[x + 1]; Block[{$IterationLimit = 30}, f[1]]
: Iteration limit of 30 exceeded.
= $Aborted
It is common to use scoping constructs for function definitions with local variables:
>> fac[n_] := Module[{k, p}, p = 1; For[k = 1, k <= n, ++k, p *= k]; p]
>> fac[10]
= 3628800
>> 10!
= 3628800
##
</section>
<section title="Formatting Output">
The way results are formatted for output in \Mathics is rather sophisticated, as compatibility to the way \Mathematica does things is one of the design goals. It can be summed up in the following procedure:
<ol>
<li>The result of the query is calculated.
<li>The result is stored in 'Out' (which '%' is a shortcut for).
<li>Any 'Format' rules for the desired output form are applied to the result. In the console version of \Mathics, the result is formatted as 'OutputForm'; 'MathMLForm' for the 'StandardForm' is used in the interactive Web version; and 'TeXForm' for the 'StandardForm' is used to generate the \LaTeX version of this documentation.
<li>'MakeBoxes' is applied to the formatted result, again given either 'OutputForm', 'MathMLForm', or 'TeXForm' depending on the execution context of \Mathics. This yields a new expression consisting of "box constructs".
<li>The boxes are turned into an ordinary string and displayed in the console, sent to the browser, or written to the documentation \LaTeX file.
</ol>
As a consequence, there are various ways to implement your own formatting strategy for custom objects.
You can specify how a symbol shall be formatted by assigning values to 'Format':
>> Format[x] = "y";
>> x
= y
This will apply to 'MathMLForm', 'OutputForm', 'StandardForm', 'TeXForm', and 'TraditionalForm'.
>> x // InputForm
= x
You can specify a specific form in the assignment to 'Format':
>> Format[x, TeXForm] = "z";
>> x // TeXForm
= \text{z}
Special formats might not be very relevant for individual symbols, but rather for custom functions (objects):
>> Format[r[args___]] = "<an r object>";
>> r[1, 2, 3]
= <an r object>
You can use several helper functions to format expressions:
<dl>
<dt>'Infix[$expr$, $op$]'
<dd>formats the arguments of $expr$ with infix operator $op$.
<dt>'Prefix[$expr$, $op$]'
<dd>formats the argument of $expr$ with prefix operator $op$.
<dt>'Postfix[$expr$, $op$]'
<dd>formats the argument of $expr$ with postfix operator $op$.
<dt>'StringForm[$form$, $arg1$, $arg2$, ...]'
<dd>formats arguments using a format string.
</dl>
>> Format[r[args___]] = Infix[{args}, "~"];
>> r[1, 2, 3]
= 1 ~ 2 ~ 3
>> StringForm["`1` and `2`", n, m]
= n and m
There are several methods to display expressions in 2-D:
<dl>
<dt>'Row[{...}]'
<dd>displays expressions in a row.
<dt>'Grid[{{...}}]'
<dd>displays a matrix in two-dimensional form.
<dt>'Subscript[$expr$, $i1$, $i2$, ...]'
<dd>displays $expr$ with subscript indices $i1$, $i2$, ...
<dt>'Superscript[$expr$, $exp$]'
<dd>displays $expr$ with superscript (exponent) $exp$.
</dl>
>> Grid[{{a, b}, {c, d}}]
= a b
.
. c d
>> Subscript[a, 1, 2] // TeXForm
= a_{1,2}
If you want even more low-level control over expression display, override 'MakeBoxes':
>> MakeBoxes[b, StandardForm] = "c";
>> b
= b
## this will be displayed as c in the browser and LaTeX documentation
This will even apply to 'TeXForm', because 'TeXForm' implies 'StandardForm':
>> b // TeXForm
= c
Except some other form is applied first:
>> b // OutputForm // TeXForm
= b
'MakeBoxes' for another form:
>> MakeBoxes[b, TeXForm] = "d";
>> b // TeXForm
= d
You can cause a much bigger mess by overriding 'MakeBoxes' than by sticking to 'Format', e.g. generate invalid XML:
>> MakeBoxes[c, MathMLForm] = "<not closed";
>> c // MathMLForm
= <not closed
However, this will not affect formatting of expressions involving 'c':
>> c + 1 // MathMLForm
= ...
That\'s because 'MathMLForm' will, when not overridden for a special case, call 'StandardForm' first.
'Format' will produce escaped output:
>> Format[d, MathMLForm] = "<not closed";
>> d // MathMLForm
= ...
>> d + 1 // MathMLForm
= ...
For instance, you can override 'MakeBoxes' to format lists in a different way:
>> MakeBoxes[{items___}, StandardForm] := RowBox[{"[", Sequence @@ Riffle[MakeBoxes /@ {items}, " "], "]"}]
>> {1, 2, 3}
= {1, 2, 3}
#> {1, 2, 3} // TeXForm
= \left[1 2 3\right]
However, this will not be accepted as input to \Mathics anymore:
>> [1 2 3]
: Expression cannot begin with "[1 2 3]" (line 1 of "<test>").
>> Clear[MakeBoxes]
By the way, 'MakeBoxes' is the only built-in symbol that is not protected by default:
>> Attributes[MakeBoxes]
= {HoldAllComplete}
'MakeBoxes' must return a valid box construct:
>> MakeBoxes[squared[args___], StandardForm] := squared[args] ^ 2
>> squared[1, 2]
= squared[1, 2]
## different in LaTeX and MathML
X> squared[1, 2] // TeXForm
: Power[squared[1, 2], 2] is not a valid box structure.
=
The desired effect can be achieved in the following way:
>> MakeBoxes[squared[args___], StandardForm] := SuperscriptBox[RowBox[{MakeBoxes[squared], "[", RowBox[Riffle[MakeBoxes[#]& /@ {args}, ","]], "]"}], 2]
>> squared[1, 2]
= squared[1, 2]
#> squared[1, 2] // TeXForm
= \text{squared}\left[1,2\right]^2
You can view the box structure of a formatted expression using 'ToBoxes':
>> ToBoxes[m + n]
= RowBox[{m, +, n}]
The list elements in this 'RowBox' are strings, though string delimiters are not shown in the default output form:
>> InputForm[%]
= RowBox[{"m", "+", "n"}]
##
</section>
<section title="Graphics Introduction Examples">
Two-dimensional graphics can be created using the function 'Graphics' and a list of graphics primitives. For three-dimensional graphics see the following section. The following primitives are available:
<dl>
<dt>'Circle[{$x$, $y$}, $r$]'
<dd>draws a circle.
<dt>'Disk[{$x$, $y$}, $r$]'
<dd>draws a filled disk.
<dt>'Rectangle[{$x1$, $y1$}, {$x2$, $y2$}]'
<dd>draws a filled rectangle.
<dt>'Polygon[{{$x1$, $y1$}, {$x2$, $y2$}, ...}]'
<dd>draws a filled polygon.
<dt>'Line[{{$x1$, $y1$}, {$x2$, $y2$}, ...}]'
<dd>draws a line.
<dt>'Text[$text$, {$x$, $y$}]'
<dd>draws text in a graphics.
</dl>
>> Graphics[{Circle[{0, 0}, 1]}]
= -Graphics-
>> Graphics[{Line[{{0, 0}, {0, 1}, {1, 1}, {1, -1}}], Rectangle[{0, 0}, {-1, -1}]}]
= -Graphics-
Colors can be added in the list of graphics primitives to change the drawing color. The following ways to specify colors are supported:
<dl>
<dt>'RGBColor[$r$, $g$, $b$]'
<dd>specifies a color using red, green, and blue.
<dt>'CMYKColor[$c$, $m$, $y$, $k$]'
<dd>specifies a color using cyan, magenta, yellow, and black.
<dt>'Hue[$h$, $s$, $b$]'
<dd>specifies a color using hue, saturation, and brightness.
<dt>'GrayLevel[$l$]'
<dd>specifies a color using a gray level.
</dl>
All components range from 0 to 1. Each color function can be supplied with an additional argument specifying the desired opacity ("alpha") of the color. There are many predefined colors, such as 'Black', 'White', 'Red', 'Green', 'Blue', etc.
>> Graphics[{Red, Disk[]}]
= -Graphics-
Table of hues:
>> Graphics[Table[{Hue[h, s], Disk[{12h, 8s}]}, {h, 0, 1, 1/6}, {s, 0, 1, 1/4}]]
= -Graphics-
##
Colors can be mixed and altered using the following functions:
<dl>
<dt>'Blend[{$color1$, $color2$}, $ratio$]'