Skip to content

Instantly share code, notes, and snippets.

@gakuzzzz
Last active May 18, 2017 13:50
Show Gist options
  • Save gakuzzzz/e38fe8f67d2c76ff5e6ad3a67b31d49a to your computer and use it in GitHub Desktop.
Save gakuzzzz/e38fe8f67d2c76ff5e6ad3a67b31d49a to your computer and use it in GitHub Desktop.
TailRec<BigInteger> fib(final BigInteger n) {
return n.compareTo(two) < 0
? TailRec.done(n)
: Optional.ofNullable(memo.get(n)).map(TailRec::done).orElseGet(() ->
TailRec.call(() -> fib(n.subtract(one))).flatMap(a ->
TailRec.call(() -> fib(n.subtract(two)).map(b -> {
final BigInteger m2 = a.add(b);
memo.put(n, m2);
return m2;
}))
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment