Expressions Structure

Heads

For any expression the part before the square brackets is known as the Head of the expression and happily there is the conveniently named Head function extract it!

Head@<|1 -> 2, 3 -> 4, 5 -> 6|>

(*Out:*)

Association

The Head of an expression can be anything:

Head@(f[1][<|a -> b|>][3])

(*Out:*)

f[1][<|a -> b|>]

Head@"a"[b]

(*Out:*)

"a"

Head@( (12 s^2)[2])

(*Out:*)

12 s^2

Parts

Everything following the Head in the expression is simply a part of the expression and can be extracted with the Part function:

Part[((12 s^2)[2]), 1]

(*Out:*)

2

Part[{1, 2, 3}, 2]

(*Out:*)

2

Part also has an alias [[ ]]

{1, 2, 3}[[2]]

(*Out:*)

2

Because so often one needs the first or last components of an expression there are two dedicated functions to getting these parts:

First@Range[10]

(*Out:*)

1

Last@Range[10]

(*Out:*)

10

There is also the function Rest which will take the second through last parts of an expression:

Rest@(A @@ Range[10])

(*Out:*)

A[2, 3, 4, 5, 6, 7, 8, 9, 10]

There is also the function Take which takes spans from an expression

Take[B @@ Range[10], {3, 5}]

(*Out:*)

B[3, 4, 5]

Manipulating Expressions

Mathematica also supports the manipulation of expressions through a wide series of functions, a few of which will be explained here and more which will be explained later:

Insert takes an expression and inserts another expression in the index specified as its third argument

Insert[{1, 2, 4}, "Hi", -1]

(*Out:*)

{1, 2, 4, "Hi"}

Insert[A[1, 2, 4], "Hi", -2]

(*Out:*)

A[1, 2, "Hi", 4]

Insert[Graphics3D[{Sphere[]}, ImageSize -> Small], 
 Sphere[{2, 2, 2}, .5], {1, -1}]

(*Out:*)

21-3675499559684164904

Append and Prepend take an expression and add an element at the end and beginning respectively

Append[Graphics3D[Sphere[], ImageSize -> Small], 
 Lighting -> "Neutral"]

(*Out:*)

21-6663125985827735989

Delete and Drop both remove parts from an expression. Delete drops a single part:

Delete[A[1, 2, 3, 4, 5], 4]

(*Out:*)

A[1, 2, 3, 5]

Drop removes a span of parts

Drop[A[1, 2, 3, 4, 5], -2]

(*Out:*)

A[1, 2, 3]

Sequence

Often one wants to do something like stick the arguments of one expression inside another one. For this purpose there is a special Head Sequence

A[1, 2, 3, Sequence[1, 2, 3]]

(*Out:*)

A[1, 2, 3, 1, 2, 3]

Or demonstrating how to put a list inside the expression:

A[1, 2, 3, Sequence @@ {1, 2, 3}]

(*Out:*)

A[1, 2, 3, 1, 2, 3]

Sequence generally represents a sequence of arguments which will be used without a Head . It is used most often in pattern matching and function definitions, but has many uses.

results matching ""

    No results matching ""