Last active
December 16, 2015 08:19
-
-
Save danveloper/5405437 to your computer and use it in GitHub Desktop.
Memoized Fibonacci calculation using lambdas in Java 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MemoizedLambdaFib { | |
interface MemoizedFunction<T, R> { | |
enum Cache { | |
_; | |
Map<Object, Object> vals = new HashMap<>(); | |
} | |
R calc(T t); | |
public default R apply(T t) { | |
if (!Cache._.vals.containsKey(t)) { | |
Cache._.vals.put(t, calc(t)); | |
} | |
return (R)Cache._.vals.get(t); | |
} | |
} | |
static final MemoizedFunction<Integer, Integer> fib = (Integer n) -> { | |
if (n == 0 || n == 1) return n; | |
return fib.apply(n - 1)+fib.apply(n-2); | |
}; | |
public static void main(String[] args) { | |
System.out.println(fib.apply(20)); | |
} | |
} |
Great comment! Thank you for letting me know abou computeIfAbsent. Sorry I didn't see this sooner!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe that with the addition of the method computeIfAbsent in the interface Map, this can be greatly simplified to:
With this code you can go up to fibonacci(92) without getting long overflow miscalculations.