# Testing a certain function over multiple levels

I regularly want to test if a certain function, here foo, gives the expected result when mapping it over n - level - matrices.

My naive approach is to write:

m1 = Range@3;
m2 = {m1, m1};
m3 = {m2, m2};
m4 = {m3, m3};


Then I test:

Map[foo, m1, {ArrayDepth@m1 - 1}];
(* ... *)
Map[foo, m4, {ArrayDepth@m4 - 1}];


The m1-case correctly gives:

foo[{1, 2, 3}],


and the m4-case correctly gives:

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


(foo should always map over the innermost level).

I am now looking for a more elegant and automated solution, possibly a oneliner like:

(m[#] = BuildLevels[Range@3,4]) & /@ Range@4


but don' t know how to implement it in a short and efficient way.

-
How about m4 /. l : {__Integer} :> foo[l] ? –  mfvonh May 27 at 19:02
Just to add to that. @Kuba's answer will be faster than mine and is generally preferable if your expression has a regular structure. Mine may work better (or at least may require less typing) if the expression is unstructured. So {m1, m2, m3, m4} /. l : {__Integer} :> foo[l] also works. –  mfvonh May 27 at 19:17
Dear mfvonh, yes that is elegent and works, but only after having defined m1 ... m4. Dear kuba, "m" doesn't work because it is not defined in the above example. Couldn't one use in this case an automatic assignment to an indexed variable like m[1] ... m[4] ? –  eldo May 27 at 19:18
@Kuba - yes, I just wanted to answer "brilliant", but for one reason or the other one has to use at least 15 characters. Many many thanks - D –  eldo May 27 at 19:27

m[0] = {1, 2, 3};
m[n_] := m[n] = {#, #} &[m[n - 1]]


And you can test each m[i] with:

Map[foo, m[5], {-2}]

{{{{{foo[{1,2,3}],foo[{1,2,3}]},{foo[{1,2,3}],foo[{1,2,3}]}},{{foo[{1,2,3}],foo[{1,2,3}]},{foo[{1,2,3}],foo[{1,2,3}]}}},{{<<1>>,{<<1>>}},<<1>>}},<<1>>}


or different approach:

    ClearAll[mm]
mm[0] = {1, 2, 3};
mm[n_] := Nest[Partition[#, 2] &, ConstantArray[mm[0], 2^(n)], n - 1]

-
Brilliant --------- –  eldo May 27 at 19:23
@eldo I'm glad it works as you need. –  Kuba May 27 at 19:28