Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Mathematica use an underscore when defining parameters?

Tags:

For example if I was defining the following function

exprod[n_] := Expand[Product[x + i, {i, 1, n}]]

Then why is the underscore after the variable n, necessary in the function definition? Where does this style come from or is it specific only to the Mathematica programming language?

like image 470
EthanLWillis Avatar asked May 21 '12 16:05

EthanLWillis


People also ask

What does pattern mean in Mathematica?

Introduction to Mathematica patterns. Patterns are used to represent classes of expressions. For example, f[_] stands for any expression of the form f[anything].


1 Answers

The underscore comes from pattern matching.

The x_ matches anything and this anything is bound to the name x in the body of the function.

l[x_ * y_] := l[x] + l[y];

Then in l[2*z] first the expression 2*z is matched against the pattern x_ * y_ . Then x is bound to 2 and y is bound to z. Then the expression l[x] + l[y] is evaluated, and the result becomes l[2]+l[z].

Now say we want to define the value of l on e to be 1. Do we write l[e] := 1 or l[e_] := 1 ?

One says that l to (literally) the variable e must be 1. The other says that l to something gives 1.

http://reference.wolfram.com/mathematica/tutorial/Introduction-Patterns.html

like image 114
soegaard Avatar answered Oct 15 '22 17:10

soegaard