`card-based memoized` in Java8?

In my previous question here

Infinite Fibonacci Sequence with Memoized in Java 8

I asked how to write code to define an infinite Fibonacci sequence in compressed math using memoization with a Java8 thread.

Fortunately, I have an answer, and the code below looks good:

LongStream fibs = Stream .iterate( new long[]{1, 1}, f -> new long[]{f[1], f[0] + f[1]} ) .mapToLong(f -> f[0]); fibs .limit(30) .forEach(System.out::println); 

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 + 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040

Although the presentation of the function code style in Java8 still bothers me, I could rightly confirm that this matches the mathematical definition of a fibonacci sequence.

Computing speed assumes that she remembers a function, and he says

You can take your memoized fibonacci (x) based on the map and make an endless stream from it as follows:

What is map-based memoized in Java8?

In addition, I could not follow the logical role

.mapToLong(f -> f[0]);

Can you explain. Any links / documentation are also welcome. Thanks.

+2
source share
1 answer

As Misha said, this is the Supplier<Long> functional interface , which is stored in memory, because it stores two private variables n1 and n2 . Then the object has a mutable state and has side effects. This can cause problems when using parallelization.

 new Supplier<Long>() { private long n1 = 1; private long n2 = 2; @Override public Long get() { long fibonacci = n1; long n3 = n2 + n1; n1 = n2; n2 = n3; return fibonacci; } } 

In the opposite direction, the solution with iterate is unchanged and ready for parallelization. It generates a stream of long arrays of size 2, starting with [1,1] and iteratively applying the function f -> new long[]{f[1], f[0] + f[1]}

 .iterate( new long[]{1, 1}, f -> new long[]{f[1], f[0] + f[1]} ) 
0
source

Source: https://habr.com/ru/post/1204378/


All Articles