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");
    }

}

Where Next?

Popular Pragmatic Bookshelf topics Top

johnp
Hi Brian, Looks like the api for tinydb has changed a little. Noticed while working on chapter 7 that the .purge() call to the db throws...
New
sdmoralesma
Title: Web Development with Clojure, Third Edition - migrations/create not working: p159 When I execute the command: user=&gt; (create-...
New
mikecargal
Title: Hands-On Rust (Chapter 11: prefab) Just played a couple of amulet-less games. With a bit of debugging, I believe that your can_p...
New
jdufour
Hello! On page xix of the preface, it says there is a community forum "… for help if your’re stuck on one of the exercises in this book… ...
New
brian-m-ops
#book-python-testing-with-pytest-second-edition Hi. Thanks for writing the book. I am just learning so this might just of been an issue ...
New
leonW
I ran this command after installing the sample application: $ cards add do something --owner Brian And got a file not found error: Fil...
New
jskubick
I’m under the impression that when the reader gets to page 136 (“View Data with the Database Inspector”), the code SHOULD be able to buil...
New
Charles
In general, the book isn’t yet updated for Phoenix version 1.6. On page 18 of the book, the authors indicate that an auto generated of ro...
New
adamwoolhether
Is there any place where we can discuss the solutions to some of the exercises? I can figure most of them out, but am having trouble with...
New
mert
AWDWR 7, page 152, page 153: Hello everyone, I’m a little bit lost on the hotwire part. I didn’t fully understand it. On page 152 @rub...
New

Other popular topics Top

Devtalk
Hello Devtalk World! Please let us know a little about who you are and where you’re from :nerd_face:
New
dasdom
No chair. I have a standing desk. This post was split into a dedicated thread from our thread about chairs :slight_smile:
New
PragmaticBookshelf
Design and develop sophisticated 2D games that are as much fun to make as they are to play. From particle effects and pathfinding to soci...
New
AstonJ
Thanks to @foxtrottwist’s and @Tomas’s posts in this thread: Poll: Which code editor do you use? I bought Onivim! :nerd_face: https://on...
New
New
Margaret
Hello content creators! Happy new year. What tech topics do you think will be the focus of 2021? My vote for one topic is ethics in tech...
New
gagan7995
API 4 Path: /user/following/ Method: GET Description: Returns the list of all names of people whom the user follows Response [ { ...
New
PragmaticBookshelf
Author Spotlight Rebecca Skinner @RebeccaSkinner Welcome to our latest author spotlight, where we sit down with Rebecca Skinner, auth...
New
PragmaticBookshelf
Author Spotlight: Tammy Coron @Paradox927 Gaming, and writing games in particular, is about passion, vision, experience, and immersio...
New
First poster: bot
zig/http.zig at 7cf2cbb33ef34c1d211135f56d30fe23b6cacd42 · ziglang/zig. General-purpose programming language and toolchain for maintaini...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: