# NullReturn from list building module [closed]

This is similar to this question, but I'm still having issues. I've written a function that makes a list of 3D vectors with every combination of of numbers up to a given value n.

BuildSet1[n_] := Module[{combos, list, place},
combos = n^3;
place = 1;
list = Table[0, combos];
For[x = 1, x < n + 1, x++,
For[y = 1, y < n + 1, y++,
For[z = 1, z < n + 1, z ++,
list[[place]] = {x, y, z};
place++]]];
Return[list]]


Which returns for n=2: Null Return[{{1, 1, 1}, {1, 1, 2}, {1, 2, 1}, {1, 2, 2}, {2, 1, 1}, {2, 1, 2}, {2, 2, 1}, {2, 2, 2}}]

Now for sanity I immediately wrote another function:

test[a_] := Module[{b},
b = {0};
b[[1]] = a;
Return[b]]


which returns for n=2: {2}

What am I doing wrong?

• list = Table[0, {combos}]; – Manuel --Moe-- G Jun 5 '17 at 18:18
• Isn't Mathematica giving you a syntax warning? It is interpreting your code as For[..]; * Return[b], and it usually gives a warning when it does this. Also, try not to use Return, as it is completely superfluous here, and in general Return does not always behave in a way that you might expect. Finally, it is much simpler to use Tuples[{1,2}, 3]. – Carl Woll Jun 5 '17 at 18:18
• @Manuel--Moe--G. There is nothing wrong with list = Table[0, combos] – m_goldberg Jun 6 '17 at 18:34
• Why not make use of the power of Mathematica, rather than trying to do it by brute force. I suggest you try buildSet[n_Integer /; n > 0] := Tuples[Range[n], 3] – m_goldberg Jun 6 '17 at 18:41
• I'm voting to close this question as off-topic because there isn't really any serious correctness issue with the OP's code and, therefore, no real question. – m_goldberg Jun 6 '17 at 19:07

I think your code works. There are few things about it that I find too ugly to look at, so I would at least rewrite it as

buildSet[n_Integer /; n > 0] :=
Module[{list, place, x, y, z},
place = 1;
list = Table[0, n^3];
For[x = 1, x < n + 1, x++,
For[y = 1, y < n + 1, y++,
For[z = 1, z < n + 1, z++, list[[place++]] = {x, y, z}]]];
list]

buildSet[3]

{{1, 1, 1}, {1, 1, 2}, {1, 1, 3}, {1, 2, 1}, {1, 2, 2}, {1, 2, 3}, {1, 3, 1},
{1, 3, 2}, {1, 3, 3}, {2, 1, 1}, {2, 1, 2}, {2, 1, 3}, {2, 2, 1}, {2, 2, 2},
{2, 2, 3}, {2, 3, 1}, {2, 3, 2}, {2, 3, 3}, {3, 1, 1}, {3, 1, 2}, {3, 1, 3},
{3, 2, 1}, {3, 2, 2}, {3, 2, 3}, {3, 3, 1}, {3, 3, 2}, {3, 3, 3}}


We're talking only correctness up to now. If we add conciseness and efficiency to the discussion, then I would recommend

buildSet[n_Integer /; n > 0] := Tuples[Range[n], 3]


as a major improvement.