Last active
August 29, 2015 14:12
-
-
Save benwaffle/f60dcb94cf18bb7d41d1 to your computer and use it in GitHub Desktop.
memoize a java function
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
import java.util.*; | |
import java.util.function.Function; | |
public class Memoize { | |
static interface F<T,R> extends Function<T,R> {} | |
// not thread safe | |
static <T,R> F<T, R> memoize(F<T, R> f) { | |
Map<T, R> cache = new HashMap<>(); | |
return (x) -> { | |
cache.putIfAbsent(x, f.apply(x)); | |
return cache.get(x); | |
}; | |
} | |
static int longComputation(int x) { | |
try { Thread.sleep(1000); } catch (Exception e) {} | |
return x; | |
} | |
public static void main(String[] args) { | |
F<Integer, Integer> f = memoize(Memoize::longComputation); | |
System.out.println(f.apply(3)); | |
System.out.println(f.apply(3)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment