dtonhofer

dtonhofer

Functional Programming in Java, Second Edition: Code for "Chapter 7, Ininite Collections" in two files

SimpleTimer.java

package chapter7;

import java.util.function.Supplier;

public abstract class SimpleTimer {

    public record Result<T>(long duration_ms, T result) {}

    public static <T> chapter7.SimpleTimer.Result<T> timeIt(Supplier<T> supplier) {
        long start = System.currentTimeMillis();
        T result = supplier.get();
        long stop = System.currentTimeMillis();
        return new Result<T>(stop - start, result);
    }
}

BeingLazy_InfiniteCollections.java

package chapter7;

import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class BeingLazy_InfiniteCollections {

    // If CPU cycles are of no importance...
    // "a desparate attempt", p.133

    public static boolean isPrimeVeryGorilla(final int number) {
        return number > 1 &&
                IntStream.rangeClosed(2, (int) Math.sqrt(number))
                        .noneMatch(divisor -> number % divisor == 0);
    }

    // This doesn't work as it causes an infinite recursion
    // "a desparate attempt", p.134, but with different method & parameter names

    public static List<Integer> primesUpwardsFrom_notworking(final int number) {
        if (isPrimeVeryGorilla(number)) {
            List<Integer> morePrimes = primesUpwardsFrom_notworking(number + 1);
            morePrimes.add(0, number);
            return morePrimes;
        } else {
            return primesUpwardsFrom_notworking(number + 1);
        }
    }

    // "lazy/fpij/Primes.java", p.135, but with different method & parameter names

    private static int firstPrimeAfter(final int number) {
        if (isPrimeVeryGorilla(number + 1)) {
            return number + 1;
        } else {
            return firstPrimeAfter(number + 1);
        }
    }

    // "lazy/fpij/Primes.java", p.135, but with different method & parameter names

    private static List<Integer> primesUpwardsFrom(final int fromNumber, final int count) {
        return Stream.iterate(firstPrimeAfter(fromNumber - 1), BeingLazy_InfiniteCollections::firstPrimeAfter)
                .limit(count)
                .collect(toList());
    }

    // Testing primesUpwardsFrom()
    // https://en.wikipedia.org/wiki/List_of_prime_numbers
    // https://oeis.org/A000040

    @Test
    public void generatePrimes() {
        final var shall = List.of(101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
                179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281);
        final List<Integer> primesAfter100 = primesUpwardsFrom(100, shall.size());
        final String txt = primesAfter100.stream().map(it -> Integer.toString(it)).collect(Collectors.joining(",\n"));
        System.out.println(txt);
        assertEquals(shall, primesAfter100);
    }

    // Testing primesUpwardsFrom()
    // Similar to "lazy/fpij/Primes.java" on p.136

    @Test
    public void runBookPrimes() {
        List<Integer> l1 = primesUpwardsFrom(1, 10);
        List<Integer> l2 = primesUpwardsFrom(100, 5);
        assertEquals(List.of(2, 3, 5, 7, 11, 13, 17, 19, 23, 29), l1);
        assertEquals(List.of(101, 103, 107, 109, 113), l2);
        System.out.println("10 primes from 1: " + l1);
        System.out.println("5 primes from 100: " + l2);
    }


    // It's quite slow!

    @Test
    void runBookPrimesWithTimer() {
        final int limit = 1_000_000;
        // not an actual test, just printout
        final SimpleTimer.Result<List<Integer>> stRes =
                SimpleTimer.timeIt(
                        () -> primesUpwardsFrom(2, limit)
                );
        final List<Integer> result = stRes.result();
        final String range = (result.isEmpty()) ? "" : "in range [" + result.get(0) + "," + result.get(result.size() - 1) + "] ";
        System.out.println("Using book code: finding " + result.size() + " primes " + range + "took " + stRes.duration_ms() + " ms");
    }

}

Popular Pragmatic Bookshelf topics Top

jon
Some minor things in the paper edition that says “3 2020” on the title page verso, not mentioned in the book’s errata online: p. 186 But...
New
kuroneko
Whilst the author has been careful to provide exact results for the tests elsewhere in the book (such as surds with the transformation te...
New
iPaul
page 37 ANTLRInputStream input = new ANTLRInputStream(is); as of ANTLR 4 .8 should be: CharStream stream = CharStreams.fromStream(i...
New
adamwoolhether
I’m not quite sure what’s going on here, but I’m unable to have to containers successfully complete the Readiness/Liveness checks. I’m im...
New
New
hazardco
On page 78 the following code appears: &lt;%= link_to ‘Destroy’, product, class: ‘hover:underline’, method: :delete, data: { confirm...
New
jonmac
The allprojects block listed on page 245 produces the following error when syncing gradle: “org.gradle.api.GradleScriptException: A prob...
New
kolossal
Hi, I need some help, I’m new to rust and was learning through your book. but I got stuck at the last stage of distribution. Whenever I t...
New
EdBorn
Title: Agile Web Development with Rails 7: (page 70) I am running windows 11 pro with rails 7.0.3 and ruby 3.1.2p20 (2022-04-12 revision...
New
andreheijstek
After running /bin/setup, the first error was: The foreman' command exists in these Ruby versions: That was easy to fix: gem install fore...
New

Other popular topics Top

Devtalk
Reading something? Working on something? Planning something? Changing jobs even!? If you’re up for sharing, please let us know what you’...
1021 17087 374
New
wolf4earth
@AstonJ prompted me to open this topic after I mentioned in the lockdown thread how I started to do a lot more for my fitness. https://f...
New
siddhant3030
I’m thinking of buying a monitor that I can rotate to use as a vertical monitor? Also, I want to know if someone is using it for program...
New
New
AstonJ
There’s a whole world of custom keycaps out there that I didn’t know existed! Check out all of our Keycaps threads here: https://forum....
New
AstonJ
I have seen the keycaps I want - they are due for a group-buy this week but won’t be delivered until October next year!!! :rofl: The Ser...
New
foxtrottwist
A few weeks ago I started using Warp a terminal written in rust. Though in it’s current state of development there are a few caveats (tab...
New
AstonJ
We’ve talked about his book briefly here but it is quickly becoming obsolete - so he’s decided to create a series of 7 podcasts, the firs...
New
sir.laksmana_wenk
I’m able to do the “artistic” part of game-development; character designing/modeling, music, environment modeling, etc. However, I don’t...
New
AstonJ
This is a very quick guide, you just need to: Download LM Studio: https://lmstudio.ai/ Click on search Type DeepSeek, then select the o...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: