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
page 37
ANTLRInputStream input = new ANTLRInputStream(is);
as of ANTLR 4 .8 should be:
CharStream stream = CharStreams.fromStream(i...
New
Following the steps described in Chapter 6 of the book, I’m stuck with running the migration as described on page 84:
bundle exec sequel...
New
Python Testing With Pytest - Chapter 2, warnings for “unregistered custom marks”
While running the smoke tests in Chapter 2, I get these...
New
Many tasks_proj/tests directories exist in chapters 2, 3, 5 that have tests that use the custom markers smoke and get, which are not decl...
New
Title: Hands-On Rust (Chap 8 (Adding a Heads Up Display)
It looks like
.with_simple_console_no_bg(SCREEN_WIDTH*2, SCREEN_HEIGHT*2...
New
This isn’t directly about the book contents so maybe not the right forum…but in some of the code apps (e.g. turbo/06) it sends a TURBO_ST...
New
When trying to generate the protobuf .go file, I receive this error:
Unknown flag: --go_opt
libprotoc 3.12.3
MacOS 11.3.1
Googling ...
New
I’m running Android Studio “Arctic Fox” 2020.3.1 Patch 2, and I’m embarrassed to admit that I only made it to page 8 before running into ...
New
I’m a newbie to Rails 7 and have hit an issue with the bin/Dev script mentioned on pages 112-113.
Iteration A1 - Seeing the list of prod...
New
Hi,
I am getting an error I cannot figure out on my test.
I have what I think is the exact code from the book, other than I changed “us...
New
Other popular topics
Write Elixir tests that you can be proud of. Dive into Elixir’s test philosophy and gain mastery over the terminology and concepts that u...
New
What chair do you have while working… and why?
Is there a ‘best’ type of chair or working position for developers?
New
I know that these benchmarks might not be the exact picture of real-world scenario, but still I expect a Rust web framework performing a ...
New
Please tell us what is your preferred monitor setup for programming(not gaming) and why you have chosen it.
Does your monitor have eye p...
New
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
Saw this on TikTok of all places! :lol:
Anyone heard of them before?
Lite:
New
Hi folks,
I don’t know if I saw this here but, here’s a new programming language, called Roc
Reminds me a bit of Elm and thus Haskell. ...
New
If you get Can't find emacs in your PATH when trying to install Doom Emacs on your Mac you… just… need to install Emacs first! :lol:
bre...
New
Was just curious to see if any were around, found this one:
I got 51/100:
Not sure if it was meant to buy I am sure at times the b...
New
Author Spotlight
Erin Dees
@undees
Welcome to our new author spotlight! We had the pleasure of chatting with Erin Dees, co-author of ...
New
Categories:
Sub Categories:
Popular Portals
- /elixir
- /rust
- /wasm
- /ruby
- /erlang
- /phoenix
- /keyboards
- /python
- /js
- /rails
- /security
- /go
- /swift
- /vim
- /clojure
- /emacs
- /haskell
- /java
- /svelte
- /onivim
- /typescript
- /kotlin
- /c-plus-plus
- /crystal
- /tailwind
- /react
- /gleam
- /ocaml
- /elm
- /flutter
- /vscode
- /ash
- /html
- /opensuse
- /zig
- /centos
- /deepseek
- /php
- /scala
- /react-native
- /lisp
- /textmate
- /sublime-text
- /nixos
- /debian
- /agda
- /django
- /deno
- /kubuntu
- /arch-linux
- /nodejs
- /revery
- /ubuntu
- /manjaro
- /spring
- /lua
- /diversity
- /julia
- /markdown
- /c








