|
| Language Overview |
|
At the core of Mathematica is its highly developed symbolic language, which unifies a broad range of programming paradigms, and uses its unique concept of symbolic programming to add a new level of flexibility to the very concept of programming.
|
|
|
| |
Symbolic Expressions
f[a,b,...] the basic underlying form of everything in Mathematica |
|
Lists & Expression Manipulation{...}
(List) - ...[[...]] (Part) - Table - Length - Take - Select - ... |
|
Functional Operations
...& (Function) - /@ (Map) - Nest - NestList - FoldList - Array - ... |
|
Pattern Matching
_ - __ - | - .. - /; - Cases - Position - ... |
|
Definitions & Assignments
= - := - =. - ^= - ... |
|
Logic & Tests
- - && - || - MemberQ - ... |
|
Scoping & Modularity
Module - With - Block - Dynamic - ... |
|
Procedural Programming
; - If - Do - While - Sow - Reap - ...
|
|
String Manipulation
"..." (String) - StringExpression - StringReplace - StringCases - ...
|
| Expressions |
|
At the core of Mathematica is the foundational idea that everythingdata, programs, formulas, graphics, documentscan be represented as symbolic expressions. And it is this unifying concept that underlies Mathematica's symbolic programming paradigm, and makes possible much of the unique power of the Mathematica language and system.
|
|
|
| |
Expression Structure »
FullForm the full form of an expression, without shortened syntax
TreeForm - Head - Length - Depth - Symbol - ... |
|
Transforming Expressions »
expr/.rules make replacements for any occurrence of a pattern in an expression
Applying Functions »
Map, Apply map, apply a function at any level in any expression |
|
Expression Testing »
SameQ (SameQ) - FreeQ - MemberQ - NumberQ - OrderedQ - ... |
|
Parts of Expressions »
Part (..[[..]]) numbered parts of an expression, reset using =
Position - ReplacePart - MapAt - Delete - ...
Cases find occurrences of a pattern in an expression
Structural Operations »
Flatten - Thread - Distribute - FlattenAt - Append - ... |
|
Controlling Expression Evaluation »
Hold - Evaluate - HoldFirst - HoldAll - ... |
| Rules & Patterns |
|
At the core of Mathematica's symbolic programming paradigm is the concept of transformation rules for arbitrary symbolic patterns. Mathematica's pattern language conveniently describes a very general set of classes of expressions, making possible uniquely readable, elegant and efficient programs.
|
|
|
| |
Rules »
lhs ...> rhs (Rule) representation of replacement rule
expr/.rules (ReplaceAll) apply replacement rules to an expression
RuleDelayed(:>) - ReplaceRepeated(//.) - Condition(/;) - ... |
|
Patterns »
x_ any expression, named x
x__ sequence of expressions
a|b|c alternative forms
Repeated(..) - Except - Longest - Shortest - ... |
|
Pattern Matching Functions »
Cases elements of a list or expression matching a given pattern
Position - MemberQ - MatchQ - Count - DeleteCases - ... |
|
Assignments »
lhs=rhs, lhs:=rhs make assignments for arbitrary patterns |
| Procedural Programming |
|
Mathematica stands out from traditional computer languages in supporting many programming paradigms. Procedural programming is the only paradigm available in languages like C and Java, as well as most scripting languages. Mathematica supports all standard procedural programming constructs, but often extends them through integration into its more general symbolic programming environment.
|
|
|
| |
x=value (Set) set the value for a variable
expr;expr;expr (CompoundExpression) execute expressions in sequence |
|
Assignments »
= - += - ++ - *= - AppendTo - ...
Loops »
Do - While - For - Table - Nest - ...
Conditionals »
If - Which - Switch - And(&&) - Equal(Equal) - Less(<) - ...
Flow Control »
Return - Throw - Catch - TimeConstrained - ...
Scoping Constructs »
Module - With - Block - ...
Input, Output, Etc. »
Print - Input - Pause - Import - OpenRead - ... |
| Parallel Computing |
|
Mathematica provides a uniquely integrated and automated environment for parallel computing. With zero configuration, full interactivity and seamless local and network operation, the symbolic character of the Mathematica language allows immediate support of a variety of existing and new parallel programming paradigms and data-sharing models.
|
|
|
| |
Automatic Parallelization
Parallelize evaluate an expression using automatic parallelization
ParallelTry try different computations in parallel, giving the first result obtained
Computation Setup & Broadcasting »
ParallelEvaluate evaluate an expression on all parallel subkernels
DistributeDefinitions distribute definitions to all parallel subkernels
ParallelNeeds load the same package into all parallel subkernels |
|
Data Parallelism »
ParallelMap - ParallelTable - ParallelSum - ...
ParallelCombine evaluate expressions in parallel and combine their results |
|
Concurrency Control »
ParallelSubmit submit expressions to be evaluated concurrently
WaitAll wait for all concurrent evaluations to finish
WaitNext wait for the next of a list of concurrent evaluations to finish |
|
Shared Memory & Synchronization »
SetSharedVariable specify symbols with values to synchronize across subkernels
SetSharedFunction specify functions whose evaluations are to be synchronized
$SharedVariables - $SharedFunctions - UnsetShared - CriticalSection |
|
Setup and Configuration »
LaunchKernels launch a specified number of subkernels
$KernelCount number of running subkernels
$KernelID - Kernels - AbortKernels - CloseKernels - ...
$ProcessorCount number of processor cores on the current computer |
| Package Development |
|
Mathematica is to its core a fundamentally extensible system, in which efficient, modular, reusable packages of any size can readily be created. Mathematica's symbolic program and interface architecture allows it to provide a uniquely flexible modern software development environment with many important original features.
|
|
|
| |
Modularity Constructs »
Module localize names of variables
Block localize values of variables
DynamicModule localize interface constructs |
|
Namespace Management »
BeginPackage, EndPackage set up namespaces for a package
Begin - End - $ContextPath - $Packages - Names - CellContext - ...
Package Loading & Saving
Needs load a package if needed
Save save definitions for symbols & functions
DeclarePackage - DumpSave - Encode - ... |
|
Options Management »
Options - SetOptions - OptionsPattern - OptionValue - ...
Messages »
Message - MessageName (::) - Check - Quiet - ...
Syntax Coloring
SyntaxInformation specify automatic syntax annotation |
|
Package Editing
File > New > Package (.m) create a package file to edit as a notebook
Packages from Notebooks
Initialization Cell define a cell to be used as initialization
Notebook History show editing history of a notebook |
|
Object-Oriented Definition
UpSet (^=) associate a definition with an inner construct
TagSet (/: ... =) associate a definition with any construct |
|
Bulletproofing »
Protect - AbortProtect - $VersionNumber - $SystemID - BlockRandom - ... |
| Syntax |
|
Mathematica has a rich syntax carefully designed for consistency and efficient, readable entry of Mathematica's many language, mathematical and other constructs. In addition to ordinary linear ASCII input, Mathematica also supports full 2D mathematical input.
|
|
|
| |
Basic Syntax
f[x,y] function arguments go in square brackets
Exp, Do, ... built-in symbols have names beginning with capital letters
{...} (List) - "..." (String) - e[[i]] (Part) - e[[i;;j]] (Span) |
|
Basic Operations
x=val set a value (=. to clear a value)
xEqualval test equality, or represent a symbolic equation (NotEqual for unequal)
lhs:=rhs function etc. definition
a->b, a to b rule for transformations, options, etc. (:> for delayed rule)
expr/.rule replace using a rule ("slash dot") |
|
Mathematics & Operators
+ - * / ^ (Power) - && (And) - || (Or) - ! (Not) - <> (StringJoin)
a b c spaces stand for multiplication
nn*^ee scientific notation
b^^nnnn number in a base |
|
Patterns
x_ any expression ("x blank")
x__, x___ sequences of arbitrary expressions ("x double blank", ...)
_, __, ___ unnamed patterns
x:p pattern name
p:d pattern default
.. (Repeated) - | (Alternatives) - /; (Condition) - ? (PatternTest) |
|
Pure Functions
expr& a pure function
#, #2, etc. arguments in a pure function |
|
Short Forms
f@expr prefix function application
expr//f postfix function application ("slash slash")
/@ (Map "slash at") EmptyVerySmallSquare @@, @@@ (Apply) - ~~ (StringExpression) - SameQ (SameQ) |
|
Program Syntax
expr;expr;expr sequence of commands (CompoundExpression)
<<file input a file (>>file, >>>file for outputting to a file)
(* ... *) comment
ccc`nnn symbol in context ccc |
|
Mathematica Session Syntax
% most recent output (%n for output on line n)
?x information on symbol x |
| List Manipulation |
|
Lists are central constructs in Mathematica, used to represent collections, arrays, sets and sequences of all kinds. Lists can have any structure and size, and can routinely involve even millions of elements. Well over a thousand built-in functions throughout Mathematica operate directly on lists, making lists a powerful vehicle for interoperability.
|
|
|
| |
Constructing Lists »
{a,b,...} (List) specify a list explicitly
Table make a table of values of an expression
Array make an array of any dimension from a function
Range - SparseArray - Tuples - NestList - Sow - Reap - ... |
|
Elements of Lists »
list[[...]] (Part) parts or sequences of parts (;;), resettable with =
First - Last - Take - Drop - Extract - Append - ReplacePart - ...
Select select according to a function
Cases give cases matching a pattern
Length - Position - MemberQ - DeleteDuplicates - ... |
|
Rearranging & Restructuring Lists »
Flatten flatten out nested lists
Join - Partition - Transpose - Reverse - Sort - Split - Gather - Riffle - ... |
|
Applying Functions to Lists »
Map (/@) map a function over a list: f/@{a, b, c}LongRightArrow{f[a], f[b], f[c]}
Apply (@@, @@@) apply a function to a list: f@@{a, b, c}LongRightArrowf[a, b, c]
MapIndexed - Scan - Thread - MapThread - Outer - FoldList - ... |
|
Math & Counting Operations »
{..}+{..}, etc. automatically operate in parallel on list elements
Total - Differences - Tally - Count - BinCounts - ... |
|
Displaying & Visualizing Lists »
Column - Row - Grid - ListPlot - ArrayPlot - ... |
|
Importing & Exporting Lists »
Import - Export - "Table" - "Text" - "CSV" - ... |
| Defining Variables and Functions |
|
The symbolic language paradigm of Mathematica takes the concept of variables and functions to a new level. In Mathematica a variable can not only stand for a value, but can also be used purely symbolically. And building on Mathematica's powerful pattern language, "functions" can be defined not just to take arguments, but to transform a pattern with any structure.
|
|
|
| |
x=... set a variable
f[x_]:=... define a function that takes any single argument |
|
Assignments »
Set (=) immediate assignment (right-hand side evaluated immediately)
SetDelayed (:=) delayed assignment (right-hand side evaluated only when used)
Unset (=.) unset a variable
Clear clear a function definition |
|
Function Argument Patterns »
__(BlankSequence) - p|p(Alternatives) - p:e (Optional)
Bodies of Functions »
Module, ... scope local variables
e;e;e (CompoundExpression) execute expressions in sequence
Function Attributes »
Attributes - Flat - Orderless - Listable - HoldFirst - Protected |
| Functional Programming |
|
Long viewed as an important theoretical idea, functional programming finally became truly convenient and practical with the introduction of Mathematica's symbolic language. Treating expressions like f[x] as both symbolic data and the application of a function f provides a uniquely powerful way to integrate structure and functionand an efficient, elegant representation of many common computations.
|
|
|
| |
Function (&) specify a pure function (e.g. (#+1)&)
#, ## slots for variables in a pure function |
|
Applying Functions to Lists »
Map (/@) map across a list: f/@{x, y, z}LongRightArrow{f[x], f[y], f[z]}
Apply (@@, @@@) apply to a list: f@@{x, y, z}LongRightArrowf[x, y, z]
MapIndexed map with index information: {f[x, {1}], f[y, {2}], f[z, {3}]}
MapThread - MapAt - MapAll - Scan - ... |
|
Iteratively Applying Functions »
Nest, NestList nest a function: f[f[f[x]]] etc.
Fold, FoldList fold in a list of values: f[f[f[x, 1], 2], 3] etc.
FixedPoint, FixedPointList repeatedly nest until a fixed point
NestWhile - NestWhileList - TakeWhile - LengthWhile - ... |
|
List-Oriented Functions
Select select from a list according to a function
Array create an array from a function
Sort, Split sort, split according to a function |
|
Functional Composition Operations
Identity - Composition - Operate - Through - Distribute |
| String Manipulation |
|
Integrated into the core Mathematica language is industrial-strength string manipulation, not only with ordinary regular expressions, but also with Mathematica's own powerful general symbolic string-pattern language.
|
|
|
| |
"string" a string, allowing Unicode or special characters |
|
Structural Operations
StringJoin (<>) join strings together
StringLength length of a string
StringSplit split a string into words or other units
StringTake, StringDrop take or drop parts of a string |
|
String Patterns »
StringExpression a symbolic string expression including symbolic string patterns
Longest - Shortest - Except - Whitespace - NumberString - ... |
|
Operations on Strings »
StringReplace make replacements for string patterns
StringCases find cases of string patterns
StringFreeQ test whether a string is free of a string pattern
StringCount - StringPosition - ... |
|
String Alignment & Comparison »
SequenceAlignment find matching sequences in strings
Nearest find strings nearest in edit distance
HammingDistance - EditDistance - LongestCommonSubsequence - ... |
|
Sort sort strings alphabetically or otherwise
Riffle riffle lists of objects {a, x, a, x, a, x, a}
Hash - StringFormat
DictionaryLookup look up strings in an English dictionary |
|
ToString, ToExpression convert between expressions and strings >>>
ImportString, ExportString translate many formats of strings
"XML" - "Table" - ... |
|
Character Operations »
Characters break a string into a list of characters
ToUpperCase - ToCharacterCode - LetterQ - ... |
|
Operations on File Names »
FileNameSplit - FileNameTake - FileBaseName - ExpandFileName - ... |
| External Operations |
|
Tightly integrated into Mathematica's core language is a rich set of primitives for interacting with external environments. Mathematica's symbolic architecture makes possible powerful symbolic representations for external constructs and functionalityallowing immediate application of Mathematica's sophisticated algorithms and advanced programming paradigms.
|
|
|
| |
Import & Export »
Import, Export import, export from files, pipes, URLs in hundreds of formats
File & Stream Operations »
Put(>>) - Get(<<) - OpenRead - Read - Write - BinaryRead - Find - ...
File System Operations »
FileNames - FileDate - FileHash - SetDirectory - CreateDirectory - ...
System Information »
$CommandLine - AbsoluteTime - DateList - $UserName - $MachineDomains - ... |
|
External Programs »
Run - Install - LoadJavaClass - LoadNETType - InstallService - ...
MathLink API »
LinkCreate - LinkRead - LinkWrite - LinkPatterns - ... |
|
Device Control »
CurrentValue - ControllerState - MousePosition - Dynamic - ... |
| Tuning & Debugging |
|
Mathematica's highly optimized architecture makes it easy to create programs that are both elegant and efficient. Its symbolic character lets you immediately run and test even the smallest program fragments. And it provides full-scale software engineering support, from arbitrarily detailed compilation control, to novel high-level symbolic analysis.
|
|
|
| |
Monitor dynamically monitor values during a computation
StepMonitor, EvaluationMonitor monitor built-in algorithms
Sow, Reap accumulate lists of values from within a computation |
|
Print print any expression or graphic
PrintTemporary print temporary output, cleaning up at the end of a computation
Dialog enter a subsession at any stage in a computation |
|
Evaluation > Debugger start interactive debugger |
|
Execution Tracing »
Trace - TracePrint - Stack - ...
Messages »
On switch on a single message or a group of messages
Off - Message - Check - Quiet - ... |
|
Time »
TimeConstrained constrain CPU time for a computation
Timing, AbsoluteTiming CPU and absolute timing
N - Compile - Dispatch - Hash - DumpSave - ... |
|
Memory »
Clear clear values
MemoryConstrained constrain memory usage in a computation
ByteCount - MemoryInUse - Share - Short - Compress - $HistoryLength - ... |
|
Program Tuning
Method specify particular methods for algorithmic functions to use
PerformanceGoal specify whether to optimize for quality, speed, etc.
ExampleData data for test examples
Parallelization »
Parallelize automatically parallelize computations across available processors
Dynamic Interactivity Tuning
TrackedSymbols - SynchronousUpdating - UpdateInterval
Low-Level System Optimization »
SystemOptions - ClearSystemCache - SystemInformation - ... |
|
GraphPlot lay out a symbolic call graph
Symbol Namespace »
Names - Remove - Unique - ... |
| Wolfram|Alpha Integration |
Mathematica has integrated interactive and programmatic access to the full power of the Wolfram|Alpha computational knowledge engine, using it to allow free-form linguistic input of computations and programs, as well as extensive data and computation capabilities that rely on the Wolfram|Alpha knowledge base and curated data.
|
|
|
| |
( at beginning of input) use free-form linguistics to generate Mathematica output
( at beginning of input) generate full Wolfram|Alpha output
(Ctrl+ ) enter free-form linguistics for conversion to inline Mathematica input
|
|
open/close complete Wolfram|Alpha output
Wolfram|Alpha result chosen for use in Mathematica
|
|
Programmatic Access
WolframAlpha get results in many possible forms from Wolfram|Alpha
"FullOutput" fully formatted Wolfram|Alpha output
"MathematicaParse" Mathematica expression corresponding to the query
"MathematicaResult" pure standard Mathematica result (if any)
"DataRules" a list of available exposed data
"Validate" whether the query can be interpreted by Wolfram|Alpha
"XML" raw XML data
TimeConstraint ▪ Asynchronous ▪ PodWidth ▪ AppearanceElements
|
| New in 8.0 : Core Language |
|
Built on powerful and elegant principles, the core Mathematica
language provides a uniquely deep and rich programming language that
scales from rapid prototyping to large high-performance systems.
Version 8.0 adds syntax-free linguistic input as a radical and
innovative approach to programming. It also delivers many important
performance features, such as automatic code generation, multi-core
parallelization, shared library linking, and GPU integration.
|
|
|
| |
Wolfram|Alpha Integration »
( at beginning of input) use free-form linguistics to generate Mathematica output
(Ctrl+ ) enter free-form linguistics for conversion to inline Mathematica input
WolframAlpha get results in many possible forms from Wolfram|Alpha
|
|
New Compiler Features »
Compile increase speed of computations by compiling to native code
CompilationTarget an option that specifies the target runtime for the compiled function, including C code
RuntimeAttributes an option that specifies the Listable attribute for the compiled function
Parallelization an option that specifies whether a compiled function should run in parallel
|
|
Dynamic Library Linking »
LibraryFunctionLoad load a function from a shared library into Mathematica
LibraryFunction a function that calls into a shared library
LibraryFunctionInformation information on a library function
LibraryFunctionUnload, LibraryUnload unload functions and libraries
FindLibrary, $LibraryPath find libraries resolving system-specific file extensions
|
|
GPU Computing Using CUDALink »
CUDAInformation list all CUDA device information
CUDAImageConvolve convolve images with specified kernel
CUDAFunctionLoad load a user-defined function to run on a GPU using CUDA
|
|
GPU Computing Using OpenCLLink »
OpenCLInformation list all OpenCL device information
OpenCLFunctionLoad load a user-defined function to run on a GPU using OpenCL
|
|
Generate C from Mathematica Programs »
Export export a Mathematica-compiled function into C code
CCodeGenerate export a Mathematica-compiled function into C code
|
|
Symbolic Representation of C Code »
ToCCodeString convert a symbolic C expression into a string of C code
|
|
Call C Compilers from Mathematica »
CreateExecutable create an executable from C code
CreateLibrary create a library from C code
|
|
Create and Run Scheduled Tasks »
CreateScheduledTask create a task to perform timed evaluations
RunScheduledTask schedule and run a task to perform timed evaluations
|
|
Conditionals »
ConditionalExpression represent an expression that is valid when a condition is satisfied
|
|
New in Message Handling
Assert test an assertion
$AssertFunction specify a function to apply to assertions that fail
|
|
Performance Improvements in Parallel Computing
Parallelize (modified) performance improvements, automatic distribution of definitions
LaunchKernels (modified) kernel-launching performance improvements
DistributeDefinitions (modified) definition-distribution performance improvements
|
|
|