0

When the function is defined as following

static Function1<BigInteger, BigInteger> fibonacci = Function((BigInteger value) ->
            value.equals(BigInteger.ZERO) ? BigInteger.ZERO
                    : value.equals(BigInteger.ONE) ? BigInteger.ONE
                    : value.equals(BigInteger.valueOf(2)) ? BigInteger.ONE
                    : Program.fibonacci.apply(value.subtract(BigInteger.ONE)).add(Program.fibonacci.apply(value.subtract(BigInteger.valueOf(2))))
    ).memoized();

And called

System.out.println(fibonacci.apply(BigInteger.valueOf(1000)));

It calculated very fast. However if I move the memoized() to function variable as follows

static Function1<BigInteger, BigInteger> fibonacci = Function((BigInteger value) ->
            value.equals(BigInteger.ZERO) ? BigInteger.ZERO
                    : value.equals(BigInteger.ONE) ? BigInteger.ONE
                    : value.equals(BigInteger.valueOf(2)) ? BigInteger.ONE
                    : Program.fibonacci.apply(value.subtract(BigInteger.ONE)).add(Program.fibonacci.apply(value.subtract(BigInteger.valueOf(2))))
    ); // Removed memoized() from here

And called

fibonacci.memoized().apply(BigInteger.valueOf(1000));

It takes very long as if memoized() was not applied.

What might be the reason for that?

ozgur
  • 2,549
  • 4
  • 25
  • 40
  • 1
    Because a) the recursion isn't called on the memoized form, b) the whole point of memoizing is that you need to save the memoization, not create a new memoization each time. – Louis Wasserman Nov 02 '17 at 19:32
  • I guess I got it. My Second example is memoized for only 1000. The other values are called on raw **fibonacci()**. Can you answer the question so that I accep it? – ozgur Nov 02 '17 at 19:38
  • Why you don't use Binet's formula for calculating fibonacci? http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html – Samir Nov 02 '17 at 21:37
  • 2
    @SamirAghayarov I guess this is more about experimenting functional programming using Fibonacci as a toy example, rather than a genuine need for the function's values. – Nándor Előd Fekete Nov 03 '17 at 03:37
  • @NándorElődFekete Exactly. – ozgur Nov 03 '17 at 05:35

1 Answers1

2

Because a) the recursion isn't called on the memoized form, b) the whole point of memoizing is that you need to save the memoization, not create a new memoization each time.

Program.fibonacci is defined in terms of itself, so the recursion calls that version, not the memoized version.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413