Taskcore
Use lazy sequences
Also called lazy pipeline, chain lazy operations, process an infinite sequence, generator pipeline, stream pipeline, deferred query.
Build a pipeline of lazy steps over an infinite sequence, a source, a filter and a take, to get the first n prime numbers without a list of all the candidates.
- Evidence
- Code in 10 languages
Task
Get the first n prime numbers with a pipeline of lazy steps. The function first_primes(n) returns them in increasing order. For example, first_primes(5) is [2, 3, 5, 7, 11], and first_primes(0) is an empty list.
The program does not know before it starts how many numbers it must test to find n primes. So the pipeline starts with the infinite sequence 2, 3, 4, and so on, and has three steps:
- Source. An infinite sequence of the numbers from 2. It makes a number only when the next step asks for one.
- Filter. A step that keeps the numbers that are prime. It tests a number only when the next step asks for one more prime.
- Take. A step that asks for
nprimes and then stops the pipeline.
When the take step stops, the filter stops and the source stops. The pipeline tests the numbers only up to the n-th prime. A pipeline of lists cannot do this, because the first list would have no end. Rust says of its iterators: "Iterators (and iterator adapters) are lazy. This means that just creating an iterator doesn’t do a whole lot."1 MDN says of an infinite generator: "You cannot convert seq to an array, because it is infinite."2
The test for a prime is trial division: a number k of 2 or more is prime if no d with d * d <= k divides it. The contract allows n up to 1000.
Solutions
| Language | Source | Filter | Take |
|---|---|---|---|
| Python | count(2) |
filter(is_prime, ...) |
islice(..., n) |
| JavaScript | a generator | .filter(isPrime) (iterator helper) |
.take(n).toArray() |
| TypeScript | a generator | a generator filter |
a for loop with break |
| Java | IntStream.iterate(2, k -> k + 1) |
.filter(Primes::isPrime) |
.limit(n).toArray() |
| C# | a yield return method |
.Where(IsPrime) |
.Take(n).ToArray() |
| Go | an iter.Seq[int] |
a function from iter.Seq[int] to iter.Seq[int] |
a range loop with break |
| Rust | 2.. |
.filter(...) |
.take(n).collect() |
| C | a struct that holds the next number | primes_next tests until it finds a prime |
a loop of n calls |
| C++ | std::views::iota(2) |
std::views::filter(is_prime) |
std::views::take(n) |
| Bash | a loop without end | a while read loop |
head -n "$n" |
- Python.
filtermakes "an iterator from those elements of iterable for which function is true"3.countmakes "an iterator that returns evenly spaced values beginning with start"4, andisliceis an iterator too, so the three steps run one number at a time. A test replacescountwith a source that records each number it makes, and checks that the pipeline stops at 11 forn = 5. - JavaScript. "Iterator helper methods are necessary to work with infinite iterators"2.
filterandtakeare such methods. TypeScript writes the same steps as generator functions. - Java. "Intermediate operations are always lazy."5
filteris intermediate, andlimitis a "short-circuiting stateful intermediate operation"6, so the stream stops afternprimes. - C#.
WhereandTakeare deferred and streaming: "a streaming operator performs its operation on each source element as it is read and yields the element if appropriate."7 - Go. Each step is an
iter.Seq[int]. A sequence "stops either when the sequence is finished or when yield returns false, indicating to stop the iteration early."8 Thebreakmakesyieldreturn false in the last step, and the filter then returns false to the source. - Rust. "Iterators do not have to be finite."1 The range
2..has no end, andtakemakes the pipeline finite. - C++. The views compute nothing until the loop reads them.
takeis a "view of the elements from an underlying sequence, starting at the beginning and ending at a given bound."9 - C. C has no lazy sequence in its library. The struct
primesholds the next number to test, andprimes_nextcontinues from there. This is the same idea by hand: the state of the pipeline is a small value, not a list. - Bash. The three steps are three processes in a pipeline.
head -nprints "the first num lines"10 and exits, and then the writes of the two other steps fail and they stop.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
zero:n = 0gives an empty list. The pipeline then does not need to test any number.one:first_primes(1)is[2], the only even prime.two:[2, 3], two primes with no number between them.past-a-gap:n = 31ends at 127. The numbers 114 to 126 are not prime, so the filter tests 13 numbers before it gives the last prime. The take step must wait for it and not stop early.
Pitfalls
- Python an iterator can be read only once. A generator,
filterandisliceare iterators. "Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container."11 The secondlistgets nothing, and there is no error:
from itertools import count, islice
small = islice(filter(lambda k: k % 2 == 1, count(1)), 4)
print(list(small))
print(list(small))
[1, 3, 5, 7]
[]
- Java a stream can be used only once. "A stream should be operated on (invoking an intermediate or terminal stream operation) only once."6 A second terminal operation throws an exception. Make the stream again from its source:
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
IntStream odd = IntStream.iterate(1, k -> k + 2).limit(4);
System.out.println(odd.sum());
try {
System.out.println(odd.sum());
} catch (IllegalStateException e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
16
IllegalStateException
- C# a deferred query runs again each time. The opposite fault: a C# query can be read many times, but it does all the work again each time. "Deferred execution provides the facility of query reuse since the query fetches the updated data from the data source each time query results are iterated."7 With a slow filter, call
ToListonce and use the list:
int tests = 0;
var odd = Enumerable.Range(1, 10).Where(k => { tests++; return k % 2 == 1; });
Console.WriteLine(odd.Count());
Console.WriteLine(odd.Sum());
Console.WriteLine(tests);
5
25
20
- A step that needs all the input never ends on an infinite source. A sort or a group must read the whole input before it gives the first item. Microsoft says: "Nonstreaming operators must read all the source data before they can yield a result element. Operations such as sorting or grouping fall into this category."7 Java says: "Stateful operations may need to process the entire input before producing a result."5 Put such a step after the take step, or do not use it on an infinite sequence.
- Rust an adapter that is not consumed does nothing. A
maporfilterwithout acollect, aforloop or another consumer runs no code. The compiler warns: "iterators are lazy and do nothing unless consumed"1.
Related tasks
- Take the first n items: take the first n items of a list or of an infinite sequence.
- Filter a list: keep the items of a list that pass a test.
- Map over a list: apply a function to each item of a list.
- Iterate in chunks: split a list into parts of a fixed size.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-lazy-sequences/.
from collections.abc import Iterator
from itertools import count, islice
def is_prime(k: int) -> bool:
"""Return True if k is a prime number, by trial division."""
if k < 2:
return False
d = 2
while d * d <= k:
if k % d == 0:
return False
d += 1
return True
def primes() -> Iterator[int]:
"""Return the infinite lazy sequence of the prime numbers."""
# count(2) has no end, and filter tests a number only when it is read.
return filter(is_prime, count(2))
def first_primes(n: int) -> list[int]:
"""Return the first n prime numbers."""
# islice stops after n items, so the pipeline reads only what it needs.
return list(islice(primes(), n))
test_primes.py 45 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-lazy-sequences/.
from itertools import count, islice
import pytest
import primes as mod
from primes import first_primes, primes
CASES = {
"five": (5, [2, 3, 5, 7, 11]),
"ten": (10, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]),
"twenty-five": (25, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]),
"zero": (0, []),
"one": (1, [2]),
"two": (2, [2, 3]),
"past-a-gap": (31, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127]),
}
@pytest.mark.parametrize("name", CASES)
def test_first_primes(name):
n, want = CASES[name]
assert first_primes(n) == want
def test_primes_is_lazy():
seq = primes()
assert next(seq) == 2
assert list(islice(seq, 3)) == [3, 5, 7]
def test_reads_only_what_it_needs(monkeypatch):
read = []
def counting(start):
for k in count(start):
read.append(k)
yield k
monkeypatch.setattr(mod, "count", counting)
assert first_primes(5) == [2, 3, 5, 7, 11]
# The pipeline stops at 11, the fifth prime.
assert read[-1] == 11
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
#include "primes.hpp"
#include <ranges>
bool is_prime(int k) {
if (k < 2) {
return false;
}
for (int d = 2; d * d <= k; d++) {
if (k % d == 0) {
return false;
}
}
return true;
}
std::vector<int> first_primes(std::size_t n) {
// iota(2) has no end; filter and take are views, so they compute a value
// only when the loop asks for it.
auto primes = std::views::iota(2) | std::views::filter(is_prime) | std::views::take(n);
std::vector<int> out;
for (int p : primes) {
out.push_back(p);
}
return out;
}
primes.hpp 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
#pragma once
#include <cstddef>
#include <vector>
// is_prime reports whether k is a prime number, by trial division.
bool is_prime(int k);
// first_primes returns the first n prime numbers.
std::vector<int> first_primes(std::size_t n);
test_primes.cpp 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
#include "primes.hpp"
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
using Ints = std::vector<int>;
static void check(std::string_view name, std::size_t n, const Ints &want) {
if (first_primes(n) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("five", 5, Ints{2, 3, 5, 7, 11});
check("ten", 10, Ints{2, 3, 5, 7, 11, 13, 17, 19, 23, 29});
check("twenty-five", 25, Ints{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97});
check("zero", 0, Ints{});
check("one", 1, Ints{2});
check("two", 2, Ints{2, 3});
check("past-a-gap", 31, Ints{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
import java.util.stream.IntStream;
final class Primes {
private Primes() {}
/** Returns true if k is a prime number, by trial division. */
static boolean isPrime(int k) {
if (k < 2) {
return false;
}
for (int d = 2; d * d <= k; d++) {
if (k % d == 0) {
return false;
}
}
return true;
}
/** Returns the infinite lazy stream of the prime numbers. */
static IntStream primes() {
// iterate has no end, and filter is lazy: it runs only for the numbers that are read.
return IntStream.iterate(2, k -> k + 1).filter(Primes::isPrime);
}
/** Returns the first n prime numbers. */
static int[] firstPrimes(int n) {
// limit is short-circuiting, so the stream stops after n primes.
return primes().limit(n).toArray();
}
}
PrimesTest.java 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class PrimesTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("five", 5, new int[] {2, 3, 5, 7, 11}),
Arguments.of("ten", 10, new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}),
Arguments.of("twenty-five", 25, new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}),
Arguments.of("zero", 0, new int[] {}),
Arguments.of("one", 1, new int[] {2}),
Arguments.of("two", 2, new int[] {2, 3}),
Arguments.of("past-a-gap", 31, new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void firstPrimes(String name, int n, int[] want) {
assertArrayEquals(want, Primes.firstPrimes(n));
}
@Test
void primesIsLazy() {
assertEquals(7, Primes.primes().skip(3).findFirst().getAsInt());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
#include "primes.h"
bool is_prime(int k) {
if (k < 2) {
return false;
}
for (int d = 2; d * d <= k; d++) {
if (k % d == 0) {
return false;
}
}
return true;
}
struct primes primes_start(void) {
return (struct primes){2};
}
int primes_next(struct primes *seq) {
// Test the numbers from seq->next until one is prime; keep the place.
while (!is_prime(seq->next)) {
seq->next++;
}
return seq->next++;
}
size_t first_primes(size_t n, int *out) {
struct primes seq = primes_start();
for (size_t i = 0; i < n; i++) {
out[i] = primes_next(&seq);
}
return n;
}
primes.h 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
#ifndef PRIMES_H
#define PRIMES_H
#include <stdbool.h>
#include <stddef.h>
// is_prime reports whether k is a prime number, by trial division.
bool is_prime(int k);
// struct primes is a lazy infinite sequence of the prime numbers. It holds
// only the next number to test.
struct primes {
int next;
};
// primes_start returns a sequence that begins at 2.
struct primes primes_start(void);
// primes_next returns the next prime number of the sequence.
int primes_next(struct primes *seq);
// first_primes writes the first n prime numbers to out and returns n. out
// must have room for n numbers.
size_t first_primes(size_t n, int *out);
#endif
test_primes.c 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
#include "primes.h"
#include <stdio.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
// An empty list has a 0 in it, because C has no empty array.
#define CHECK(name, n, expected) \
do { \
const int w[] = expected; \
int out[64]; \
size_t k = first_primes(n, out); \
int ok = k == (size_t)(n); \
for (size_t i = 0; ok && i < k; i++) { \
ok = out[i] == w[i]; \
} \
if (!ok) { \
fprintf(stderr, "case %s failed\n", name); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("five", 5, L(2, 3, 5, 7, 11));
CHECK("ten", 10, L(2, 3, 5, 7, 11, 13, 17, 19, 23, 29));
CHECK("twenty-five", 25, L(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97));
CHECK("zero", 0, L(0));
CHECK("one", 1, L(2));
CHECK("two", 2, L(2, 3));
CHECK("past-a-gap", 31, L(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127));
// The sequence keeps its place between calls.
struct primes seq = primes_start();
primes_next(&seq);
primes_next(&seq);
if (primes_next(&seq) != 5 || seq.next != 6) {
fprintf(stderr, "case lazy failed\n");
failures++;
}
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
using System.Collections.Generic;
using System.Linq;
public static class Primes
{
// IsPrime returns true if k is a prime number, by trial division.
public static bool IsPrime(int k)
{
if (k < 2)
{
return false;
}
for (int d = 2; d * d <= k; d++)
{
if (k % d == 0)
{
return false;
}
}
return true;
}
// Naturals is the infinite sequence start, start + 1, ... It runs only when it is read.
private static IEnumerable<int> Naturals(int start)
{
for (int i = start; ; i++)
{
yield return i;
}
}
// All is the infinite lazy sequence of the prime numbers.
public static IEnumerable<int> All()
{
// Where uses deferred execution: it tests a number only when it is read.
return Naturals(2).Where(IsPrime);
}
// First returns the first n prime numbers.
public static int[] First(int n)
{
return All().Take(n).ToArray();
}
}
PrimesTests.cs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
using System.Linq;
using Xunit;
public sealed class PrimesTests
{
public static TheoryData<string, int, int[]> Cases => new()
{
{ "five", 5, new[] { 2, 3, 5, 7, 11 } },
{ "ten", 10, new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 } },
{ "twenty-five", 25, new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 } },
{ "zero", 0, new int[0] },
{ "one", 1, new[] { 2 } },
{ "two", 2, new[] { 2, 3 } },
{ "past-a-gap", 31, new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void First(string name, int n, int[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Primes.First(n));
}
[Fact]
public void AllIsLazy()
{
Assert.Equal(7, Primes.All().Skip(3).First());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
/** Returns true if k is a prime number, by trial division. */
export function isPrime(k) {
if (k < 2) {
return false;
}
for (let d = 2; d * d <= k; d++) {
if (k % d === 0) {
return false;
}
}
return true;
}
/** The infinite sequence start, start + 1, ... It runs only when it is read. */
function* naturals(start) {
for (let i = start; ; i++) {
yield i;
}
}
/** Returns the infinite lazy sequence of the prime numbers. */
export function primes() {
// Iterator helpers are lazy: filter tests a number only when it is read.
return naturals(2).filter(isPrime);
}
/**
* Returns the first n prime numbers.
* @param {number} n from 0
* @returns {number[]}
*/
export function firstPrimes(n) {
return primes().take(n).toArray();
}
primes.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { firstPrimes, primes } from "./primes.js";
const cases = [
["five", 5, [2, 3, 5, 7, 11]],
["ten", 10, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]],
["twenty-five", 25, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]],
["zero", 0, []],
["one", 1, [2]],
["two", 2, [2, 3]],
["past-a-gap", 31, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127]],
];
for (const [name, n, want] of cases) {
test(name, () => {
assert.deepEqual(firstPrimes(n), want);
});
}
test("primes is lazy", () => {
const seq = primes();
assert.equal(seq.next().value, 2);
assert.equal(seq.next().value, 3);
assert.equal(seq.next().value, 5);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
/** Returns true if k is a prime number, by trial division. */
export function isPrime(k: number): boolean {
if (k < 2) {
return false;
}
for (let d = 2; d * d <= k; d++) {
if (k % d === 0) {
return false;
}
}
return true;
}
/** The infinite sequence start, start + 1, ... It runs only when it is read. */
function* naturals(start: number): Generator<number> {
for (let i = start; ; i++) {
yield i;
}
}
/** Keeps the items that pass the test; it reads its input only when it is read. */
function* filter<T>(items: Iterable<T>, test: (item: T) => boolean): Generator<T> {
for (const item of items) {
if (test(item)) {
yield item;
}
}
}
/** Returns the infinite lazy sequence of the prime numbers. */
export function primes(): Generator<number> {
return filter(naturals(2), isPrime);
}
/** Returns the first n prime numbers. */
export function firstPrimes(n: number): number[] {
const out: number[] = [];
if (n === 0) {
return out;
}
// The break stops the pipeline after n items.
for (const p of primes()) {
out.push(p);
if (out.length === n) {
break;
}
}
return out;
}
primes.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { firstPrimes, primes } from "./primes.ts";
const cases: [string, number, number[]][] = [
["five", 5, [2, 3, 5, 7, 11]],
["ten", 10, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]],
["twenty-five", 25, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]],
["zero", 0, []],
["one", 1, [2]],
["two", 2, [2, 3]],
["past-a-gap", 31, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127]],
];
for (const [name, n, want] of cases) {
test(name, () => {
assert.deepEqual(firstPrimes(n), want);
});
}
test("primes is lazy", () => {
const seq = primes();
assert.equal(seq.next().value, 2);
assert.equal(seq.next().value, 3);
assert.equal(seq.next().value, 5);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
// Package primes gives the prime numbers through a lazy sequence.
package primes
import "iter"
// IsPrime reports whether k is a prime number, by trial division.
func IsPrime(k int) bool {
if k < 2 {
return false
}
for d := 2; d*d <= k; d++ {
if k%d == 0 {
return false
}
}
return true
}
// Naturals is the infinite sequence start, start + 1, ...
func Naturals(start int) iter.Seq[int] {
return func(yield func(int) bool) {
for i := start; ; i++ {
if !yield(i) {
return
}
}
}
}
// Filter keeps the values of seq that pass test. It reads seq only when it is read.
func Filter(seq iter.Seq[int], test func(int) bool) iter.Seq[int] {
return func(yield func(int) bool) {
for v := range seq {
if test(v) && !yield(v) {
return
}
}
}
}
// All is the infinite lazy sequence of the prime numbers.
func All() iter.Seq[int] {
return Filter(Naturals(2), IsPrime)
}
// First returns the first n prime numbers.
func First(n int) []int {
out := []int{}
if n == 0 {
return out
}
// The break makes yield return false, and each step of the pipeline stops.
for p := range All() {
out = append(out, p)
if len(out) == n {
break
}
}
return out
}
primes_test.go 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
package primes
import (
"slices"
"testing"
)
var cases = []struct {
name string
n int
want []int
}{
{"five", 5, []int{2, 3, 5, 7, 11}},
{"ten", 10, []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}},
{"twenty-five", 25, []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}},
{"zero", 0, []int{}},
{"one", 1, []int{2}},
{"two", 2, []int{2, 3}},
{"past-a-gap", 31, []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127}},
}
func TestFirst(t *testing.T) {
for _, c := range cases {
if got := First(c.n); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
func TestReadsOnlyWhatItNeeds(t *testing.T) {
last := 0
counted := func(yield func(int) bool) {
for v := range Naturals(2) {
last = v
if !yield(v) {
return
}
}
}
got := []int{}
for p := range Filter(counted, IsPrime) {
got = append(got, p)
if len(got) == 5 {
break
}
}
if last != 11 {
t.Errorf("the pipeline read up to %d, want 11", last)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
/// Returns true if k is a prime number, by trial division.
pub fn is_prime(k: u32) -> bool {
if k < 2 {
return false;
}
let mut d = 2;
while d * d <= k {
if k % d == 0 {
return false;
}
d += 1;
}
true
}
/// Returns the infinite lazy sequence of the prime numbers.
pub fn primes() -> impl Iterator<Item = u32> {
// 2.. has no end, and filter is lazy: it runs only for the numbers that are read.
(2..).filter(|&k| is_prime(k))
}
/// Returns the first n prime numbers.
pub fn first_primes(n: usize) -> Vec<u32> {
primes().take(n).collect()
}
tests/primes_test.rs 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-lazy-sequences/.
use algo_use_lazy_sequences::{first_primes, primes};
#[test]
fn cases() {
let cases: Vec<(&str, usize, Vec<u32>)> = vec![
("five", 5, vec![2, 3, 5, 7, 11]),
("ten", 10, vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29]),
("twenty-five", 25, vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]),
("zero", 0, vec![]),
("one", 1, vec![2]),
("two", 2, vec![2, 3]),
("past-a-gap", 31, vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127]),
];
for (name, n, want) in cases {
assert_eq!(first_primes(n), want, "{name}");
}
}
#[test]
fn primes_is_lazy() {
assert_eq!(primes().nth(3), Some(7));
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-lazy-sequences/.
# is_prime K
# Returns 0 if K is a prime number, by trial division.
is_prime() {
local k=$1 d
(( k < 2 )) && return 1
for ((d = 2; d * d <= k; d++)); do
(( k % d == 0 )) && return 1
done
return 0
}
# naturals START
# Prints START, START + 1, ... without end. It stops when its output closes.
naturals() {
local i
for ((i = $1; ; i++)); do
printf '%d\n' "$i" || return 0
done
}
# primes
# Prints the prime numbers without end. It reads one number at a time from
# naturals, so it does only the work that the reader asks for.
primes() {
local k
naturals 2 | while read -r k; do
is_prime "$k" || continue
printf '%d\n' "$k" || break
done
}
# first_primes N
# Prints the first N prime numbers, one on each line.
first_primes() {
(( $1 > 0 )) || return 0
primes | head -n "$1"
}
test_primes.bats 27 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-lazy-sequences/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/primes.sh"
}
check() { # check WANT N
local want got
# %b turns each \n in WANT into a newline. The x keeps the trailing
# newlines, which $(...) removes.
want=$(printf '%b' "$1"; printf x)
got=$(first_primes "$2"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "five" { check "2\n3\n5\n7\n11\n" 5; }
@test "ten" { check "2\n3\n5\n7\n11\n13\n17\n19\n23\n29\n" 10; }
@test "twenty-five" { check "2\n3\n5\n7\n11\n13\n17\n19\n23\n29\n31\n37\n41\n43\n47\n53\n59\n61\n67\n71\n73\n79\n83\n89\n97\n" 25; }
@test "zero" { check "" 0; }
@test "one" { check "2\n" 1; }
@test "two" { check "2\n3\n" 2; }
@test "past-a-gap" { check "2\n3\n5\n7\n11\n13\n17\n19\n23\n29\n31\n37\n41\n43\n47\n53\n59\n61\n67\n71\n73\n79\n83\n89\n97\n101\n103\n107\n109\n113\n127\n" 31; }
@test "is_prime" { is_prime 97; run ! is_prime 91; }
References
- Module std::iter, The Rust Standard Library, Laziness; Infinity
- Iterator, MDN Web Docs, Iterator helper methods
- Built-in Functions, Python 3.14 documentation, filter
- itertools, Python 3.14 documentation, count; islice
- Package java.util.stream, Java SE 21 API, Streams differ from collections; Stream operations and pipelines
- Interface Stream, Java SE 25 API, class description
- Introduction to LINQ Queries in C#, Microsoft Learn, Classification of standard query operators by manner of execution
- Package iter, Go 1.26.5 standard library, Iterators; Seq
- std::ranges::take_view, std::ranges::views::take, cppreference.com, description
- GNU Coreutils manual, 5.1 head
- Glossary, Python 3.14 documentation, iterator
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag QVNFSC Edit this page History Report an error Markdown