Created
June 8, 2014 08:43
-
-
Save ezsi/1306b85ad55a9f7c15f8 to your computer and use it in GitHub Desktop.
Function decorators using Java8 lambdas
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
package repl; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.function.Function; | |
public class Tools { | |
public static final boolean CACHE_ON = true; | |
public static final boolean TIMER_ON = true; | |
private static <T, K> Function<T, K> timer(Function<T, K> f) { | |
if( !TIMER_ON ) return f; | |
Function<T, K> fun = (args) -> { | |
long time = System.currentTimeMillis(); | |
K ret = f.apply(args); | |
time = System.currentTimeMillis() - time; | |
System.out.println("time = " + time); | |
return ret; | |
}; | |
return fun; | |
} | |
private static <T, K> Function<T, K> cache(Function<T, K> f) { | |
if(!CACHE_ON) return f; | |
Map<T, K> cache = new HashMap<>(); | |
Function<T, K> fun = (args) -> { | |
K ret = cache.get(args); | |
if( ret == null ) { | |
ret = f.apply(args); | |
cache.put(args, ret); | |
} | |
return ret; | |
}; | |
return fun; | |
} | |
private static Function<Integer, Long> fib = cache(n -> { | |
if (n == 0 || n == 1) return 1L; | |
return Tools.fib.apply(n - 1) + Tools.fib.apply(n - 2); | |
}); | |
public static void main(String[] args) { | |
Function<Integer, Long> tfib = timer(fib); | |
long res = tfib.apply(45); | |
System.out.println("res = " + res); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment