Back: Programming
Previous: Avoid Procedural Loops
Next: Syntax of = := ==

Programming in Mathematica

Pattern Matching; using Head and tests

Head: which kind of expression



listD = {x, 17, 17-2I, 3/4, x^2, {a,b,c}, a + b}
Head  /@  listD

	                  3   2
	{x, 17, 17 - 2 I, -, x , {a, b, c}, a + b}
	                  4
	
	{Symbol, Integer, Complex, Rational, Power, List, Plus}



f[x]         = 2 x;            (* for specific value "x" *)
f[x_]        = 3 x;            (* general case *)
f[x_Integer] = x + 100;        (* for integers only *)
f[x_Plus]    = "A Sum";        (* for sums only *)


{f[x], f[A], f[3.8], f[ 7 ], f[ 7. ], f[a+b], f[7+3]}

	         3
	{2 x, 3 A  (1 + 2 A), 1415.7, 107, 15435., A Sum, 110}


  listD
  f  /@  listD

	                  3   2
	{x, 17, 17 - 2 I, -, x , {7, b, 9}, 7 + b}
	                  4
	

	                              405     6         2
	{2 x, 117, 473733 - 237738 I, ---, 3 x  (1 + 2 x ), 
	                              128
	 
	                   3
	        {15435, 3 b  (1 + 2 b), 41553}, A Sum}


Tests: other attributes of an expression

Tests include Negative, NonNegative, Positive, NumberQ, EvenQ, OddQ, PrimeQ, VectorQ, MatrixQ.

g[x_?Negative] =  "negative";
g[x_?Positive] =  "positive";
g[x_]          =  "dunno";

{ g[3], g[-3], g[I-3], g[XXX], g[Pi], g[E^(I Pi)] }

	{positive, negative, dunno, dunno, positive, negative}