:

## Applying a function to nested elements

Maple
A poster on the usenet group comp.soft-sys.math.maple asked how to do the following more simply:
```A:={ { [1,2],[3,4] } , { [5,6],[7,8] } }:
map(x->map(y->map(f,y),x),A);

{{[f(1), f(2)], [f(3), f(4)]}, {[f(5), f(6)], [f(7), f(8)]}}
```
As has been discussed here recently, this can be readily done using evalindets. For example,
```evalindets(A, list, integer, f);
{{[f(3), f(4)], [f(1), f(2)]}, {[f(5), f(6)], [f(7), f(8)]}}
```
However, there are cases where evalindets may not be so easily applied, that is, where it is tricky to isolate the element we want to operate on using just a type match. Instead we would prefer to operate on all elements at a particular depth in the structure. One way to do that is with the following procedure
```maptolev := proc(lev::nonnegint, f, e)
apply(seq(map[lev-i],i=0..lev-1),f,e);
end proc:
```
The first parameter, lev, specifies the depth of the elements to which f is applied. If lev=0 then f is applied to the entire structure, that is maptolev(0,f,A) = f(A). Here is how it is used to solve the given example:
```maptolev(3, f, A);
{{[f(1), f(2)], [f(3), f(4)]}, {[f(5), f(6)], [f(7), f(8)]}}
```

﻿