package java8.test; import java.util.Arrays; public class Main { interface Duo { int apply(int n, Duo g); } interface Trio { int apply(int n, int prod, Trio g); } interface Quad { int apply(int n, int a, int b, Quad g); } static Duo factorial = (n, g) -> n > 0 ? n * g.apply(n - 1, g) : 1; static Trio tailFactorial = (n, p, g) -> n == 0 ? p : g.apply(n - 1, n * p, g); static Quad fibonacci = (n, a, b, g) -> n == 0 ? a : g.apply(n - 1, b, a + b, g); public static void main(String[] args) { Arrays.asList(args) .stream() .map(Integer::decode) .map(n -> String.format( Arrays.asList("factorial(%d) = %d", "tailFactorial(%d) = %d", "fibonacci(%d) = %d") .stream() .reduce("", (a, b) -> a + (a.isEmpty() ? a : System.getProperty("line.separator")) + b), n, factorial.apply(n, factorial), n, tailFactorial.apply(n, 1, tailFactorial), n, fibonacci.apply(n, 0, 1, fibonacci))) .forEach(System.out::println); } }
Monday, February 03, 2014
Because Java 8 and because Lambda
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment