# How to get this nesting working?

I want to nest each element inside the previous at the mid point. How can I do this by indexing a very large list?

   {5/24,mid,19/24}/.mid->
{7/24,mid,17/24}/.mid->
{11/24,mid,13/24}


({5/24, {7/24, {11/24, mid, 13/24}, 17/24}, 19/24}) Yes, it's Goldbach that creates the lists. The sample is 5+19, 7+17 and 11+13 with the sum, 24, as the denominator. After the nest: we notice 5,7 on the left and 17,19 on the right. We put the sum of 17,19 divided by 2 (the mid point) into our solver to create the next chain link. I haven't shown any of that code, because the last time I did, I found out the ones who viewed were math phobic.

• I don't understand the sequence 5, 7, 11,... in the numerators. Ditto for the upper bounds. Commented Apr 5, 2023 at 1:21
• They are primes, since I am experimenting with the twin prime conjecture. Commented Apr 5, 2023 at 1:30
• What I meant was that you reference a very large list. Since the only lists in the question are of the form {a, mid, b}, it's unclear where the a's and the b's come from or how the large list is to be modified. Commented Apr 5, 2023 at 1:32
• the triplet is just one of many. The a''s and b's are called p and q in my twin prime solver. Observation: only the last item in a twin, the others are twins with low prime on the left and the high prime on the rigjt---after the nesting. We rely on symmetry. Commented Apr 5, 2023 at 1:52
• I had to Reverse@list to get one working; otherwise it was tough choice. I did remove mid and the denominators, Thanks. Commented Apr 5, 2023 at 11:27

alist = {{5/24, 19/24}, {7/24, 17/24}, {11/24, 13/24}};

Fold[Riffle[#2, {#1}] &, Reverse@alist]


$$\left\{\frac{5}{24},\left\{\frac{7}{24},\left\{\frac{11}{24},\frac{13}{24}\right\},\frac{17}{24}\right\},\frac{19}{24}\right\}$$

• +1, I'll do some timings on large lists before accepting either answer. Commented Apr 5, 2023 at 1:34
• To see how it folds step by step: FoldList[Riffle[#2, {#1}] &, Reverse@alist] // Grid
– Syed
Commented Apr 5, 2023 at 1:36

I'm assuming that mid is just a placeholder. So, you could do something like this:

list = {{11, 13}, {7, 17}, {5, 19}};
Fold[Insert[#2, #1, 2] &, list]


{5, {7, {11, 13}, 17}, 19}

(I've removed the denominators just for clarity.)

• +1, Can we put a list name on the right? Commented Apr 5, 2023 at 1:25
• yep. see my update. Commented Apr 5, 2023 at 1:26
• hmm. looking at your comment, were you wanting to start with {5,7,11,13,17,19} and insert the brackets, or do you have the pairs in a list already like I assumed in my answer? Commented Apr 5, 2023 at 1:32
• I start with the right-most twin prime and build the rest. I'm interested in building a chain of twin primes. Commented Apr 5, 2023 at 1:40