6

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?

GambitSquared
  • 2,311
  • 15
  • 23
  • oops ... ({#, Power[#, 2]} & @ Range[3, 6] // Transpose // ArrayReshape[#, {2, 2, 2}] &) == ({#, # #} & @ Range[3, 6] // Transpose // ArrayReshape[#, {2, 2, 2}] &) == want – user1066 Jul 15 '17 at 22:55
  • @tomd Thanks! Then this would be even shorter: {#, # #} & /@ Range[3, 6] // ArrayReshape[#, {2, 2, 2}] & – GambitSquared Jul 16 '17 at 08:59

3 Answers3

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

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

eldo
  • 67,911
  • 5
  • 60
  • 168
5
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}}}

kglr
  • 394,356
  • 18
  • 477
  • 896
4
BlockMap[{{#1[[1]], #[[1]]^2}, {#1[[2]], #[[2]]^2}} &, Range[3, 6], 2]
(* {{{3, 9}, {4, 16}}, {{5, 25}, {6, 36}}} *)
Ali Hashmi
  • 8,950
  • 4
  • 22
  • 42