I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

Largest difference between adjacent primes/Factor

From Rosetta Code
USING: arrays formatting kernel lists lists.lazy math math.order
math.primes.lists sequences ;
 
lprimes dup cdr lzip [ first2 2dup swap - -rot 3array ] lmap-lazy
[ second 1e6 < ] lwhile { 0 } [ max ] foldl
 
"Largest difference in adjacent primes under a million: %d between %d and %d.\n" vprintf
Output:
Largest difference in adjacent primes under a million: 114 between 492113 and 492227.

Explanation

Snippet Comment Data stack (the bottom is the top)
lprimes an infinite lazy list of primes L{ 2 3 5 7 ... }
dup duplicate top of stack L{ 2 3 5 7 ... }
L{ 2 3 5 7 ... }
cdr take the tail L{ 2 3 5 7 ... }
L{ 3 5 7 11 ... }
lzip combine two lists into a list of pairs L{ { 2 3 } { 3 5 } { 5 7 } { 7 11 } ... }
[ first2 2dup swap - -rot 3array ] a quotation that prepends a pair's difference to itself L{ { 2 3 } { 3 5 } { 5 7 } { 7 11 } ... }
[ first2 2dup swap - -rot 3array ]
lmap-lazy apply quotation lazily to each element of a list L{ { 1 2 3 } { 2 3 5 } { 2 5 7 } { 4 7 11 } ... }


At this point, let's take a look inside the quotation for the element { 7 11 } to see how it works.

Snippet Comment Data stack (the bottom is the top)
{ 7 11 }
first2 place first two elements of a sequence on the data stack 7
11
2dup duplicate top two objects on data stack 7
11
7
11
swap swap top two objects on data stack 7
11
11
7
- subtract 7
11
4
-rot put top of stack third from top 4
7
11
3array make a sequence from three objects { 4 7 11 }


Back to the regularly scheduled program...

Snippet Comment Data stack (the bottom is the top)
L{ { 1 2 3 } { 2 3 5 } { 2 5 7 } { 4 7 11 } ... }
[ second 1e6 < ] lwhile take from the list while the second element of each list element is less than a million L{ { 1 2 3 } { 2 3 5 } ... { 20 999983 1000003 } }
{ 0 } [ max ] foldl take the maximum element, using { 0 } as a seed { 114 492113 492227 }

At this point, we simply use vprintf to output the answer. vprintf is like printf except it takes its arguments from a sequence instead of the data stack.