# Replace Table by functional programming

Just for learning purposes I try to create a list that looks like this: {{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}}

One way to do it is by using Table:

Table[{j + 2 i, (j + 2 i)^2}, {i, 0, 1}, {j, 3, 4}]


Now I try it using functional programming, but I failed. This is what I tried:

Nest[Map[{#, #^2} &], Range[3, 4], 2]


Is it possible to create the desired result only using Nest, Map and Range? If not, what other function should I use, without using Table, but using a Pure Function instead?

• oops ... ({#, Power[#, 2]} & @ Range[3, 6] // Transpose // ArrayReshape[#, {2, 2, 2}] &) == ({#, # #} & @ Range[3, 6] // Transpose // ArrayReshape[#, {2, 2, 2}] &) == want Commented Jul 15, 2017 at 22:55
• @tomd Thanks! Then this would be even shorter: {#, # #} & /@ Range[3, 6] // ArrayReshape[#, {2, 2, 2}] & Commented Jul 16, 2017 at 8:59

Partition[{#, # #} & /@ Range[3, 6], 2]


{{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}}

• That's not the same list! ;-) Commented Jul 15, 2017 at 22:02
• Sorry, see update
– eldo
Commented Jul 15, 2017 at 22:06
• Ah, yes, I should have used Partition Commented Jul 15, 2017 at 22:13
Array[{#, #^2} & @@ {#2 + 2 #} &, {2, 2}, {0, 3}] (* or *)
Outer[{#, #^2} & @@ {#2 + 2 #} &, {0, 1}, Range[3, 4]]


{{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}}

Removing hard-coded parameters:

f1 = Module[{x = #[[1]], l = Length@#},
Array[{#, #^2} & @@ {#2 + l #} &, {l, l}, {0, x}]] &;
f1 @ Range[3, 4]


{{{3, 9}, {4, 16}},
{{5, 25}, {6, 36}}}

f1 @ Range[4, 6]


{{{4, 16}, {5, 25}, {6, 36}},
{{7, 49}, {8, 64}, {9, 81}},
{{10, 100}, {11, 121}, {12, 144}}}

And, similarly for Outer:

f2 = Module[{l = Length@#, x = #},
Outer[{#, #^2} & @@ {#2 + l #} &, Range[l] - 1, x]] &;

f2 @ Range[3, 4]


{{{3, 9}, {4, 16}},
{{5, 25}, {6, 36}}}

f2 @ Range[4, 6]


{{{4, 16}, {5, 25}, {6, 36}},
{{7, 49}, {8, 64}, {9, 81}},
{{10, 100}, {11, 121}, {12, 144}}}

Also

☺ = # /. ♯_ :> ({#, #^2} & @@@ ({♯ + #} & /@ {0, (♯♯ = 0; ♯♯++ & /@ #; ♯♯)})) &;

☺ @ {3, 4}


{{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}}

☺ @ Range[3, 7]


{{{3, 9}, {4, 16}, {5, 25}, {6, 36}, {7, 49}},
{{8, 64}, {9, 81}, {10, 100}, {11, 121}, {12, 144}}}

• Unfortunately there are too many brackets. OP wants  {{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}}
– eldo
Commented Jul 16, 2017 at 0:26
• @eldo, fixed it.
– kglr
Commented Jul 16, 2017 at 12:31
BlockMap[{{#1[[1]], #[[1]]^2}, {#1[[2]], #[[2]]^2}} &, Range[3, 6], 2]
(* {{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}} *)