Movatterモバイル変換


[0]ホーム

URL:


WOLFRAM

Wolfram Language & System Documentation Center
Patterns

Patterns

Introduction to Patterns
Patterns are used throughout the Wolfram Language to represent classes of expressions. A simple example of a pattern is the expressionf[x_]. This pattern represents the class of expressions with the formf[anything].
The main power of patterns comes from the fact that many operations in the Wolfram Language can be done not only with single expressions, but also with patterns that represent whole classes of expressions.
You can use patterns in transformation rules to specify how classes of expressions should be transformed:
You can use patterns to find the positions of all expressions in a particular class:
The basic object that appears in almost all Wolfram Language patterns is_ (traditionally called "blank" by Wolfram Language programmers). The fundamental rule is simply that _stands for any expression. On most keyboards the_ underscore character appears as the shifted version of the- dash character.
Thus, for example, the patternf[_] stands for any expression of the formf[anything]. The patternf[x_] also stands for any expression of the formf[anything], but gives the namex to the expressionanything, allowing you to refer to it on the righthand side of a transformation rule.
You can put blanks anywhere in an expression. What you get is a pattern which matches all expressions that can be made by "filling in the blanks" in any way.
f[n_]
f with any argument, namedn
f[n_,m_]
f with two arguments, namedn andm
x^n_
x to any power, with the power namedn
x_^n_
any expression to any power
a_+b_
a sum of two expressions
{a1_,a2_}
a list of two expressions
f[n_,n_]
f with twoidentical arguments
Some examples of patterns.
You can construct patterns for expressions with any structure:
One of the most common uses of patterns is for "destructuring" function arguments. If you make a definition forf[list_], then you need to use functions likePart explicitly in order to pick out elements of the list. But if you know for example that the list will always have two elements, then it is usually much more convenient instead to give a definition instead forf[{x_,y_}]. Then you can refer to the elements of the list directly asx andy. In addition, the Wolfram Language will not use the definition you have given unless the argument off really is of the required form of a list of two expressions.
Here is one way to define a function which takes a list of two elements, and evaluates the first element raised to the power of the second element:
Here is a much more elegant way to make the definition, using a pattern:
A crucial point to understand is that Wolfram Language patterns represent classes of expressions with a givenstructure. One pattern will match a particular expression if the structure of the pattern is the same as the structure of the expression, in the sense that by filling in blanks in the pattern you can get the expression. Even though two expressions may bemathematically equal, they cannot be represented by the same Wolfram Language pattern unless they have the same structure.
Thus, for example, the pattern(1+x_)^2 can stand for expressions like(1+a)^2 or(1+b^3)^2 that have the samestructure. However, it cannot stand for the expression1+2a+a^2. Although this expression ismathematically equal to(1+a)^2, it does not have the samestructure as the pattern(1+x_)^2.
The fact that patterns in the Wolfram Language specify thestructure of expressions is crucial in making it possible to set up transformation rules which change thestructure of expressions, while leaving them mathematically equal.
It is worth realizing that in general it would be quite impossible for the Wolfram Language to match patterns by mathematical, rather than structural, equivalence. In the case of expressions like(1+a)^2 and1+2a+a^2, you can determine equivalence just by using functions likeExpand andFactor. But, as discussed in"Reducing Expressions to Their Standard Form" there is no general way to find out whether an arbitrary pair of mathematical expressions are equal.
As another example, the patternx^_ will match the expressionx^2. It will not, however, match the expression1, even though this could be considered asx^0."Optional and Default Arguments" discusses how to construct a pattern for which this particular case will match. But you should understand that in all cases pattern matching in the Wolfram Language is fundamentally structural.
Thex^n_ matches onlyx^2 andx^3.1 andx can mathematically be written as, but do not have the same structure:
Another point to realize is that the structure the Wolfram Language uses in pattern matching is the full form of expressions printed byFullForm. Thus, for example, an object such as1/x, whose full form isPower[x,-1] will be matched by the patternx_^n_, but not by the patternx_/y_, whose full form isTimes[x_,Power[y_,-1]]. Again,"Optional and Default Arguments" will discuss how you can construct patterns which can match all these cases.
The expressions in the list contain explicit powers ofb, so the transformation rule can be applied:
Here is the full form of the list:
Although the Wolfram Language does not use mathematical equivalences such as when matching patterns, it does use certain structural equivalences. Thus, for example, the Wolfram Language takes account of properties such as commutativity and associativity in pattern matching.
To apply this transformation rule, the Wolfram Language makes use of the commutativity and associativity of addition:
The discussion considers only pattern objects such asx_ which can stand for any single expression. Other tutorials discuss the constructs that the Wolfram System uses to extend and restrict the classes of expressions represented by patterns.
Finding Expressions That Match a Pattern
Cases[list,form]
give the elements oflist that matchform
Count[list,form]
give the number of elements inlist that matchform
Position[list,form,{1}]
give the positions of elements inlist that matchform
Select[list,test]
give the elements oflist on whichtest givesTrue
Pick[list,sel,form]
give the elements oflist for which the corresponding elements ofsel matchform
Finding elements that match a pattern.
This gives the elements of the list which match the patternx^_:
Here is the total number of elements which match the pattern:
You can apply functions likeCases not only to lists, but to expressions of any kind. In addition, you can specify the level of parts at which you want to look.
Cases[expr,lhs->rhs]
find elements ofexpr that matchlhs, and give a list of the results of applying the transformation rule to them
Cases[expr,lhs->rhs,lev]
test parts ofexpr at levels specified bylev
Count[expr,form,lev]
give the total number of parts that matchform at levels specified bylev
Position[expr,form,lev]
give the positions of parts that matchform at levels specified bylev
Searching for parts of expressions that match a pattern.
This returns a list of the exponentsn:
The pattern_Integer matches any integer. This gives a list of integers appearing at any level:
Cases[expr,form,lev,n]
find only the firstn parts that matchform
Position[expr,form,lev,n]
give the positions of the firstn parts that matchform
Limiting the number of parts to search for.
This gives the positions of the first two powers ofx appearing at any level:
The positions are specified in exactly the form used by functions such asExtract andReplacePart discussed in"Lists":
DeleteCases[expr,form]
delete elements ofexpr that matchform
DeleteCases[expr,form,lev]
delete parts ofexpr that matchform at levels specified bylev
Deleting parts of expressions that match a pattern.
This deletes the elements which matchx^n_:
This deletes all integers appearing at any level:
ReplaceList[expr,lhs->rhs]
find all ways thatexpr can matchlhs
Finding arrangements of an expression that match a pattern.
This finds all ways that the sum can be written in two parts:
This finds all pairs of identical elements. The pattern___ stands for any sequence of elements:
Naming Pieces of Patterns
Particularly when you use transformation rules, you often need to name pieces of patterns. An object likex_ stands for any expression, but gives the expression the namex. You can then, for example, use this name on the righthand side of a transformation rule.
An important point is that when you usex_, the Wolfram Language requires that all occurrences of blanks with the same namex in a particular expression must stand for the same expression.
Thusf[x_,x_] can only stand for expressions in which the two arguments off are exactly the same.f[_,_], on the other hand, can stand for any expression of the formf[x,y], wherex andy need not be the same.
The transformation rule applies only to cases where the two arguments off are identical:
The Wolfram Language allows you to give names not just to single blanks, but to any piece of a pattern. The objectx:pattern in general represents a pattern which is assigned the namex. In transformation rules, you can use this mechanism to name exactly those pieces of a pattern that you need to refer to on the righthand side of the rule.
_
any expression
x_
any expression, to be namedx
x:pattern
an expression to be namedx, matchingpattern
Patterns with names.
This gives a name to the complete form_^_ so you can refer to it as a whole on the righthand side of the transformation rule:
Here the exponent is namedn, while the whole object isx:
When you give the same name to two pieces of a pattern, you constrain the pattern to match only those expressions in which the corresponding pieces are identical.
Here the pattern matches both cases:
Now both arguments off are constrained to be the same, and only the first case matches:
Specifying Types of Expression in Patterns
You can tell a lot about what "type" of expression something is by looking at its head. Thus, for example, an integer has headInteger, while a list has headList.
In a pattern,_h andx_h represent expressions that are constrained to have headh. Thus, for example,_Integer represents any integer, while_List represents any list.
x_h
an expression with headh
x_Integer
an integer
x_Real
an approximate real number
x_Complex
a complex number
x_List
a list
x_Symbol
a symbol
Patterns for objects with specified heads.
This replaces just those elements that are integers:
You can think of making an assignment forf[x_Integer] as like defining a functionf that must take an argument of "type"Integer.
This defines a value for the functiongamma when its argument is an integer:
The definition applies only when the argument ofgamma is an integer:
The object4. has headReal, so the definition does not apply:
This defines values for expressions with integer exponents:
The definition is used only when the exponent is an integer:
Putting Constraints on Patterns
The Wolfram Language provides a general mechanism for specifying constraints on patterns. All you need to do is to put/;condition at the end of a pattern to signify that it applies only when the specified condition isTrue. You can read the operator/; as "slashsemi", "whenever", or "provided that".
pattern/;condition
a pattern that matches only when a condition is satisfied
lhs:>rhs/;condition
a rule that applies only when a condition is satisfied
lhs:=rhs/;condition
a definition that applies only when a condition is satisfied
Putting conditions on patterns and transformation rules.
This gives a definition forfac that applies only when its argumentn is positive:
The definition forfac is used only when the argument is positive:
This gives the negative elements in the list:
You can use/; on whole definitions and transformation rules, as well as on individual patterns. In general, you can put/;condition at the end of any:= definition or:> rule to tell the Wolfram Language that the definition or rule applies only when the specified condition holds. Note that/; conditions should not usually be put at the end of= definitions or-> rules, since they will then be evaluated immediately, as discussed in"Immediate and Delayed Definitions".
Here is another way to give a definition that applies only when its argumentn is positive:
Once again, the factorial functions evaluate only when their arguments are positive:
You can use the/; operator to implement arbitrary mathematical constraints on the applicability of rules. In typical cases, you give patterns whichstructurally match a wide range of expressions, but then usemathematical constraints to reduce the range of expressions to a much smaller set.
This rule applies only to expressions that have the structurev[x_,1-x_]:
This expression has the appropriate structure, so the rule applies:
This expression, while mathematically of the correct form, does not have the appropriate structure, so the rule does not apply:
This rule applies to any expression of the formw[x_,y_], with the added restriction thaty==1-x:
The new rule does apply to this expression:
In setting up patterns and transformation rules, there is often a choice of where to put/; conditions. For example, you can put a/; condition on the righthand side of a rule in the formlhs:>rhs/;condition, or you can put it on the lefthand side in the formlhs/;condition->rhs. You may also be able to insert the condition inside the expressionlhs. The only constraint is that all the names of patterns that you use in a particular condition must appear in the pattern to which the condition is attached. If this is not the case, then some of the names needed to evaluate the condition may not yet have been "bound" in the patternmatching process. If this happens, then the Wolfram Language uses the global values for the corresponding variables, rather than the values determined by pattern matching.
Thus, for example, the condition inf[x_,y_]/;(x+y<2) will use values forx andy that are found by matchingf[x_,y_], but the condition inf[x_/;x+y<2,y_] will use the global value fory, rather than the one found by matching the pattern.
As long as you make sure that the appropriate names are defined, it is usually most efficient to put/; conditions on the smallest possible parts of patterns. The reason for this is that the Wolfram Language matches pieces of patterns sequentially, and the sooner it finds a/; condition which fails, the sooner it can reject a match.
Putting the/; condition around thex_ is slightly more efficient than putting it around the whole pattern:
You need to put parentheses around the/; piece in a case like this:
It is common to use/; to set up patterns and transformation rules that apply only to expressions with certain properties. There is a collection of functions built into the Wolfram Language for testing the properties of expressions. It is a convention that functions of this kind have names that end with the letterQ, indicating that they "ask a question".
IntegerQ[expr]
integer
EvenQ[expr]
even number
OddQ[expr]
odd number
PrimeQ[expr]
prime number
NumberQ[expr]
explicit number of any kind
NumericQ[expr]
numeric quantity
PolynomialQ[expr,{x1,x2,}]
polynomial inx1,x2,
VectorQ[expr]
a list representing a vector
MatrixQ[expr]
a list of lists representing a matrix
VectorQ[expr,NumericQ]
,
MatrixQ[expr,NumericQ]
vectors and matrices where all elements are numeric
VectorQ[expr,test]
,
MatrixQ[expr,test]
vectors and matrices for which the functiontest yieldsTrue on every element
ArrayQ[expr,d]
full array with depth matchingd
Some functions for testing mathematical properties of expressions.
The rule applies to all elements of the list that are numbers:
This definition applies only to vectors of integers:
The definition is now used only in the first case:
An important feature of all the Wolfram Language propertytesting functions whose names end inQ is that they always returnFalse if they cannot determine whether the expression you give has a particular property.
4561 is an integer, so this returnsTrue:
This returnsFalse, sincex is not known to be an integer:
Functions likeIntegerQ[x] test whetherx is explicitly an integer. With assertions likexIntegers you can useRefine,Simplify, and related functions to make inferences about symbolic variablesx.
SameQ[x,y]
or
x===y
x andy are identical
UnsameQ[x,y]
or
x=!=y
x andy are not identical
OrderedQ[{a,b,}]
a,b, are in standard order
MemberQ[expr,form]
form matches an element ofexpr
FreeQ[expr,form]
form matches nothing inexpr
MatchQ[expr,form]
expr matches the patternform
ValueQ[expr]
a value has been defined forexpr
AtomQ[expr]
expr has no subexpressions
Some functions for testing structural properties of expressions.
With==, the equation remains in symbolic form;=== yieldsFalse unless the expressions are manifestly equal:
The expressionn is not amember of the list{x,x^n}:
However,{x,x^n} is not completely free ofn:
You can useFreeQ to define a "linearity" rule forh:
Terms free ofx are pulled out of each h:
pattern?test
a pattern that matches an expression only iftest yieldsTrue when applied to the expression
Another way to constrain patterns.
The constructionpattern/;condition allows you to evaluate a condition involving pattern names to determine whether there is a match. The constructionpattern?test instead applies a functiontest to the whole expression matched bypattern to determine whether there is a match. Using? instead of/; sometimes leads to more succinct definitions.
With this definition, matches forx_ are tested with the functionNumberQ:
The definition applies only whenp has a numerical argument:
Here is a more complicated definition. Do not forget the parentheses around the pure function:
The definition applies only in certain cases:
Except[c]
a pattern that matches any expression exceptc
Except[c,patt]
a pattern that matchespatt but notc
Patterns with exceptions.
This gives all elements except 0:
Except can take a pattern as an argument:
This picks out integers that are not 0:
Except[c] is in a sense a very general pattern: it matchesanything exceptc. In many situations you instead need to useExcept[c,patt], which restricts to expressions matchingpatt that do not matchc.
Patterns Involving Alternatives
patt1|patt2|
a pattern that can have one of several forms
Specifying patterns that involve alternatives.
This definesh to givep when its argument is eithera orb:
The first two cases givep:
You can also use alternatives in transformation rules:
Here is another example, in which one of the alternatives is itself a pattern:
When you use alternatives in patterns, you should make sure that the same set of names appear in each alternative. When a pattern like(a[x_]|b[x_]) matches an expression, there will always be a definite expression that corresponds to the objectx. If you try to match a pattern like(a[x_]|b[y_]), then there still will be definite expressions corresponding tox andy, but the unmatched one will beSequence[].
Heref is used to name the head, which can be eithera orb:
Pattern Sequences
In some cases you may need to specify pattern sequences that are more intricate than things likex__ orx..; for such situations you can usePatternSequence[p1,p2,].
PatternSequence[p1,p2,]
a sequence of arguments matchingp1,p2,
Pattern sequences.
This defines a function with two or more arguments, grouping the first two:
Evaluate the function for different numbers of arguments:
This picks out the longest run of the sequencea,b in the list:
The empty sequence,PatternSequence[], is sometimes useful to specify an optional argument.
This picks out expressions with exactly one or two arguments:
Flat and Orderless Functions
Although the Wolfram Language matches patterns in a purely structural fashion, its notion of structural equivalence is quite sophisticated. In particular, it takes account of properties such as commutativity and associativity in functions likePlus andTimes.
This means, for example, that the Wolfram Language considers the expressionsx+y andy+x equivalent for the purposes of pattern matching. As a result, a pattern likeg[x_+y_,x_] can match not onlyg[a+b,a], but alsog[a+b,b].
This expression has exactly the same form as the pattern:
In this case, the expression has to be put in the formg[b+a,b] in order to have the same structure as the pattern:
Whenever the Wolfram Language encounters anorderless orcommutative function such asPlus orTimes in a pattern, it effectively tests all the possible orders of arguments to try and find a match. Sometimes, there may be several orderings that lead to matches. In such cases, the Wolfram Language just uses the first ordering it finds. For example,h[x_+y_,x_+z_] could matchh[a+b,a+b] withxa,yb,zb or withxb,ya,za. The Wolfram Language tries the casexa,yb,zb first, and so uses this match.
This can match either withxa or withxb. The Wolfram Language triesxa first, and so uses this match:
ReplaceList shows both possible matches:
As discussed in"Attributes", the Wolfram Language allows you to assign certain attributes to functions, which specify how those functions should be treated in evaluation and pattern matching. Functions can for example be assigned the attributeOrderless, which specifies that they should be treated as commutative or symmetric, and allows their arguments to be rearranged in trying to match patterns.
Orderless
commutative function:f[b,c,a], etc., are equivalent tof[a,b,c]
Flat
associative function:f[f[a],b], etc., are equivalent tof[a,b]
OneIdentity
f[f[a]], etc., are equivalent toa
Attributes[f]
give the attributes assigned tof
SetAttributes[f,attr]
addattr to the attributes off
ClearAttributes[f,attr]
removeattr from the attributes off
Some attributes that can be assigned to functions.
Plus has attributesOrderless andFlat, as well as others:
This definesq to be an orderless or commutative function:
The arguments ofq are automatically sorted into order:
The Wolfram Language rearranges the arguments ofq functions to find a match:
In addition to being orderless, functions likePlus andTimes also have the property of beingflat orassociative. This means that you can effectively "parenthesize" their arguments in any way, so that, for example,x+(y+z) is equivalent tox+y+z, and so on.
The Wolfram Language takes account of flatness in matching patterns. As a result, a pattern likeg[x_+y_] can matchg[a+b+c], withxa andy(b+c).
The argument ofg is written asa+(b+c) so as to match the pattern:
If there are no other constraints, the Wolfram Language will matchx_ to the first element of the sum:
This shows all the possible matches:
Herex_ is forced to matchb+d:
The Wolfram Language can usually apply a transformation rule to a function only if the pattern in the rule covers all the arguments in the function. However, if you have a flat function, it is sometimes possible to apply transformation rules even though not all the arguments are covered.
This rule applies even though it does not cover all the terms in the sum:
This combines two of the terms in the sum:
Functions likePlus andTimes are both flat and orderless. There are, however, some functions, such asDot, which are flat, but not orderless.
Bothx_ andy_ can match any sequence of terms in the dot product:
This assigns the attributeFlat to the functionr:
The Wolfram Language writes the expression in the formr[r[a,b],r[a,b]] to match the pattern:
The Wolfram Language writes this expression in the formr[a,r[r[b],r[b]],c] to match the pattern:
In an ordinary function that is not flat, a pattern such asx_ matches an individual argument of the function. But in a functionf[a,b,c,] that is flat,x_ can match objects such asf[b,c] which effectively correspond to a sequence of arguments. However, in the case wherex_ matches a single argument in a flat function, the question comes up as to whether the object it matches is really just the argumenta itself, orf[a]. The Wolfram Language chooses the former possibility if the function carries the attributeOneIdentity, otherwise it will first attempt to use the latter but fall back on the former.
This adds the attributeOneIdentity to the functionr:
Nowx_ matches individual arguments, withoutr wrapped around them:
The functionsPlus,Times, andDot all have the attributeOneIdentity, reflecting the fact thatPlus[x] is equivalent tox, and so on. However, in representing mathematical objects, it is often convenient to deal with flat functions that do not have the attributeOneIdentity.
Functions with Variable Numbers of Arguments
Unlessf is a flat function, a pattern likef[x_,y_] stands only for instances of the function with exactly two arguments. Sometimes you need to set up patterns that can allow any number of arguments.
You can do this usingmultiple blanks. While a single blank such asx_ stands for a single Wolfram Language expression, a double blank such asx__ stands for a sequence of one or more expressions.
Herex__ stands for the sequence of expressions(a,b,c):
Here is a more complicated definition, which picks out pairs of duplicated elements inh:
The definition is applied twice, picking out the two paired elements:
"Double blanks"__ stand for sequences of one or more expressions. "Triple blanks"___ stand for sequences of zero or more expressions. You should be very careful whenever you use triple blank patterns. It is easy to make a mistake that can lead to an infinite loop. For example, if you definep[x_,y___]:=p[x] q[y], then typing inp[a] will lead to an infinite loop, withy repeatedly matching a sequence with zero elements. Unless you are sure you want to include the case of zero elements, you should always use double blanks rather than triple blanks.
_
any single expression
x_
any single expression, to be namedx
__
any sequence of one or more expressions
x__
sequence namedx
x__h
sequence of expressions, all of whose heads areh
___
any sequence of zero or more expressions
x___
sequence of zero or more expressions namedx
x___h
sequence of zero or more expressions, all of whose heads areh
More kinds of pattern objects.
Notice that with flat functions such asPlus andTimes, the Wolfram Language automatically handles variable numbers of arguments, so you do not explicitly need to use double or triple blanks, as discussed in"Flat and Orderless Functions".
When you use multiple blanks, there are often several matches that are possible for a particular expression. By default, the Wolfram Language tries first those matches that assign the shortest sequences of arguments to the first multiple blanks that appear in the pattern. You can change this order by wrappingLongest orShortest around parts of the pattern.
Longest[p]
match the longest sequence consistent with the patternp
Shortest[p]
match the shortest sequence consistent with the patternp
Controlling the order in which matches are tried.
This gives a list of all the matches that the Wolfram Language tries:
This forces the Wolfram Language to try the longest matches forx__ first:
Many kinds of enumeration can be done by usingReplaceList with various kinds of patterns:
This effectively enumerates all sublists with at least one element:
This tries the shortest matches forx__ first:
Optional and Default Arguments
Sometimes you may want to set up functions where certain arguments, if omitted, are given "default values". The patternx_:v stands for an object that can be omitted, and if so, will be replaced by the default valuev.
This defines a functionj with a required argumentx, and optional argumentsy andz, with default values1 and2, respectively:
The default value ofz is used here:
Now the default values of bothy andz are used:
x_:v
an expression which, if omitted, is taken to have default valuev
x_h:v
an expression with headh and default valuev
x_.
an expression with a builtin default value
Pattern objects with default values.
Some common Wolfram Language functions have builtin default values for their arguments. In such cases, you need not explicitly give the default value inx_:v, but instead you can use the more convenient notationx_. in which a builtin default value is assumed.
x_+y_.
default fory is0
x_y_.
default fory is1
x_^y_.
default fory is1
Some patterns with optional pieces.
Herea matches the patternx_+y_. withy taken to have the default value 0:
BecausePlus is a flat function, a pattern such asx_+y_ can match a sum with any number of terms. This pattern cannot, however, match a single term such asa. However, the patternx_+y_. contains an optional piece, and can match either an explicit sum of terms in which bothx_ andy_ appear, or a single termx_, withy taken to be0.
Using constructs such asx_., you can easily construct single patterns that match expressions with several different structures. This is particularly useful when you want to match several mathematically equal forms that do not have the same structure.
The pattern matchesg[a^2], but notg[a+b]:
By giving a pattern in which the exponent is optional, you can match both cases:
The patterna_.+b_.x_ matches any linear function ofx_:
In this case,b1:
Hereb1 anda0:
Standard Wolfram Language functions such asPlus andTimes have builtin default values for their arguments. You can also set up defaults for your own functions, as described in"Patterns".
Sometimes it is convenient not to assign a default value to an optional argument; such arguments can be specified with the help ofPatternSequence[].
p|PatternSequence[]
optional patternp with no default value
Optional argument without a default value.
The pattern matches an optional second argument of2, without a default value:
Setting Up Functions with Optional Arguments
When you define a complicated function, you will often want to let some of the arguments of the function be "optional". If you do not give those arguments explicitly, you want them to take on certain "default" values.
Builtin Wolfram Language functions use two basic methods for dealing with optional arguments. You can choose between the same two methods when you define your own functions in the Wolfram Language.
The first method is to have the meaning of each argument determined by its position, and then to allow one to drop arguments, replacing them by default values. Almost all builtin Wolfram Language functions that use this method drop arguments from the end. For example, the builtin functionFlatten[list,n] allows you to drop the second argument, which is taken to have a default value ofInfinity.
You can implement this kind of "positional" argument using_: patterns.
f[x_,k_:kdef]:=value
a typical definition for a function whose second argument is optional, with default valuekdef
Defining a function with positional arguments.
This defines a function with an optional second argument. When the second argument is omitted, it is taken to have the default valueInfinity:
Here is a function with two optional arguments:
The Wolfram Language assumes that arguments are dropped from the end. As a resultm here gives the value ofn1, whilen2 has its default value of2:
The second method that builtin Wolfram Language functions use for dealing with optional arguments is to give explicit names to the optional arguments, and then to allow their values to be given using transformation rules. This method is particularly convenient for functions likePlot which have a very large number of optional parameters, only a few of which usually need to be set in any particular instance.
The typical arrangement is that values for "named" optional arguments can be specified by including the appropriate transformation rules at the end of the arguments to a particular function. Thus, for example, the ruleJoined->True, which specifies the setting for the named optional argumentJoined, could appear asListPlot[list,Joined->True].
When you set up named optional arguments for a functionf, it is conventional to store the default values of these arguments as a list of transformation rules assigned toOptions[f].
f[x_,OptionsPattern[]]:=value
a typical definition for a function with zero or more named optional arguments
OptionValue[name]
the value of a named optional argument in the body of the function
Named arguments.
This sets up default values for two named optional argumentsopt1 andopt2 in the functionfn:
Here is the definition for a functionfn which allows zero or more named optional arguments to be specified:
With no optional arguments specified, the default rule foropt2 is used:
If you explicitly give a rule foropt2, it will override the default rules stored inOptions[fn]:
FilterRules[opts,Options[name]]
the rules inopts used as options by the functionname
FilterRules[opts,Except[Options[name]]]
the rules inopts not used as options by the functionname
Filtering options.
Sometimes when you write a function you will want to pass on options to functions that it calls.
Here is a simple function that solves a differential equation numerically and plots its solution:
With no options given, the default options forNDSolve andPlot are used:
This changes the method used byNDSolve and the color in the plot:
Repeated Patterns
expr..
a pattern or other expression repeated one or more times
expr...
a pattern or other expression repeated zero or more times
Repeated patterns.
Multiple blanks such asx__ allow you to give patterns in which sequences of arbitrary expressions can occur. The Wolfram Language pattern repetition operators.. and... allow you to construct patterns in which particular forms can be repeated any number of times. Thus, for example,f[a..] represents any expression of the formf[a],f[a,a],f[a,a,a], and so on.
The patternf[a..] allows the argumenta to be repeated any number of times:
This pattern allows any number ofa arguments, followed by any number ofb arguments:
Here each argument can be eithera or b:
You can use.. and... to represent repetitions of any pattern. If the pattern contains named parts, then each instance of these parts must be identical.
This defines a function whose argument must consist of a list of pairs:
The definition applies in this case:
With this definition, the second elements of all the pairs must be the same:
The definition applies in this case:
The patternx.. can be extended to two arguments to control the number of repetitions more precisely.
p..
or
Repeated[p]
a pattern or other expression repeated one or more times
Repeated[p,max]
a pattern repeated up tomax times
Repeated[p,{min,max}]
a pattern repeated betweenmin andmax times
Repeated[p,{n}]
a pattern repeated exactlyn times
Controlling the number of repetitions.
This finds from two to three repetitions of the argumenta:
Verbatim Patterns
Verbatim[expr]
an expression that must be matched verbatim
Verbatim patterns.
Here thex_ in the rule matches any expression:
TheVerbatim tells the Wolfram Language that only the exact expressionx_ should be matched:
Patterns for Some Common Types of Expression
Using the objects described in "Introduction to Patterns", you can set up patterns for many kinds of expressions. In all cases, you must remember that the patterns must represent the structure of the expressions in the Wolfram Language internal form, as shown byFullForm.
Especially for some common kinds of expressions, the standard output format used by the Wolfram Language is not particularly close to the full internal form. But it is the internal form that you must use in setting up patterns.
n_Integer
an integern
x_Real
an approximate real numberx
z_Complex
a complex numberz
Complex[x_,y_]
a complex numberx+iy
Complex[x_Integer,y_Integer]
a complex number where both real and imaginary parts are integers
(r_Rational|r_Integer)
rational number or integerr
Rational[n_,d_]
a rational number
(x_/;NumberQ[x]&&Im[x]==0)
a real number of any kind
(x_/;NumberQ[x])
a number of any kind
Some typical patterns for numbers.
Here are the full forms of some numbers:
The rule picks out each piece of the complex numbers:
The fact that these expressions have different full forms means that you cannot usex_+Iy_ to match a complex number:
The pattern here matches both ordinary integers, and complex numbers where both the real and imaginary parts are integers:
As discussed in"Symbolic Computation", the Wolfram Language puts all algebraic expressions into a standard form, in which they are written essentially as a sum of products of powers. In addition, ratios are converted into products of powers, with denominator terms having negative exponents, and differences are converted into sums with negated terms. To construct patterns for algebraic expressions, you must use this standard form. This form often differs from the way the Wolfram Language prints out the algebraic expressions. But in all cases, you can find the full internal form usingFullForm[expr].
Here is a typical algebraic expression:
This is the full internal form of the expression:
This is what you get by applying a transformation rule to all powers in the expression:
x_+y_
a sum of two or more terms
x_+y_.
a single term or a sum of terms
n_Integerx_
an expression with an explicit integer multiplier
a_.+b_.x_
a linear expressiona+bx
x_^n_
xn withn0,1
x_^n_.
xn withn0
a_.+b_.x_+c_.x_^2
a quadratic expression with nonzero linear term
Some typical patterns for algebraic expressions.
This pattern picks out linear functions ofx:
x_List orx:{___}
a list
x_List/;VectorQ[x]
a vector containing no sublists
x_List/;VectorQ[x,NumberQ]
a vector of numbers
x:{___List} orx:{{___}...}
a list of lists
x_List/;MatrixQ[x]
a matrix containing no sublists
x_List/;MatrixQ[x,NumberQ]
a matrix of numbers
x:{{_,_}...}
a list of pairs
Some typical patterns for lists.
This defines a function whose argument must be a list containing lists with either one or two elements:
The definition applies in the second and third cases:
An Example: Defining Your Own Integration Function
Now that we have introduced the basic features of patterns in the Wolfram Language, we can use them to give a more or less complete example. We will show how you could define your own simple integration function in the Wolfram Language.
From a mathematical point of view, the integration function is defined by a sequence of mathematical relations. By setting up transformation rules for patterns, you can implement these mathematical relations quite directly in the Wolfram Language.
mathematical form
Wolfram Languagedefinition
integrate[y_+z_,x_]:=integrate[y,x]+integrate[z,x]
( independent of)
integrate[c_y_,x_]:=cintegrate[y,x]/;FreeQ[c,x]
integrate[c_,x_]:=cx/;FreeQ[c,x]
,
integrate[x_^n_.,x_]:=x^(n+1)/(n+1)/;FreeQ[n,x]&&n!=-1
integrate[1/(a_.x_+b_.),x_]:=Log[ax+b]/a/;FreeQ[{a,b},x]
integrate[Exp[a_.x_+b_.],x_]:=Exp[ax+b]/a/;FreeQ[{a,b},x]
Definitions for an integration function.
This implements the linearity relation for integrals::
The associativity ofPlus makes the linearity relation work with any number of terms in the sum:
This makesintegrate pull out factors that are independent of the integration variablex:
The Wolfram Language tests each term in each product to see whether it satisfies theFreeQ condition, and so can be pulled out:
This gives the integral of a constant:
Now the constant term in the sum can be integrated:
This gives the standard formula for the integral of. By using the patternx_^n_., rather thanx_^n_, we include the case of:
Now this integral can be done completely:
Of course, the builtin integration functionIntegrate (with a capitalI) could have done the integral anyway:
Here is the rule for integrating the reciprocal of a linear function. The patterna_.x_+b_. stands for any linear function ofx:
Here botha andb take on their default values:
Here is a more complicated case. The symbola now matches2p:
You can go on and add many more rules for integration. Here is a rule for integrating exponentials:

Related Guides

Top

[8]ページ先頭

©2009-2025 Movatter.jp