Apply

First I define (lst) which will be used to demonstrate Apply.

(h@@lst) simply changes the head of list to h.

Starting with Mathematica 4.0 we could use (h@@@lst) to apply a head to all sub-expressions at a specific level.

(h@@lst) is normally equivalent to Apply[h, expr] and (h@@@lst) is normally equivalent to Apply[h, lst, 1] as demonstrated in the next cell.

If you use Apply in packages you write and you need to make the package highly reliable you should be completely explicit by using things like

Apply[h, expr, Heads→False] or Apply[h, expr, 1, Heads->False] since the user of your package may have changed the default option using SetOptions[Apply, Heads→True].

The next example changes the heads at levels 1 and 2 to h.

The next example changes the heads at all levels from 0 down to level 2.

Fortunately we can Apply a function to an atomic expression without getting an error message. In that case we simply get the atom back.

The heads we are changing don't have to be lists and they don't have to be the same. Here I make a more general expression to demonstrate this.

This changes the head Plus to h.

This changes the head Times to h.

This changes the heads g1, g2, g3, and g4 to (h).

Heads Option

Apply has a Heads option with the default setting (Heads→False). I needed help from David Park to come up with some examples here. In the next input Apply is used with the default setting (Heads→False), and the only sub-expression whose head is changed are Part[expr,1]→g1[2] and Part[expr,2]→g2[3]. Not including heads these are the only sub-expressions at level 1.

Now the previous example is repeated using (Heads→True) and (h) is applied to the sub-expression Part[expr,0]→f[y]. The expression f[y] is the head of (expr) and Apply only affects the heads when the setting (Heads→True) is used.

Also read "Further Examples" at the end of the Apply documentation in the Help Browser.

Created by Mathematica (May 16, 2004)