Advertisement
NLinker

Define factorial as lambda

Jun 9th, 2017
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.76 KB | None | 0 0
  1. @FunctionalInterface
  2. public interface Function2<A1, A2, R> {
  3.     R apply(A1 a1, A2 a2);
  4. }
  5.  
  6. // first solution
  7. class Run {
  8.  
  9.     public static class Self<T> {
  10.         public final Function2<Self<T>, T, T> func;
  11.         public Self(Function2<Self<T>, T, T> func) {
  12.             this.func = func;
  13.         }
  14.     }
  15.  
  16.     public static final Function<Long, Long> factorial = n -> {
  17.         final Self<Long> trampoline = new Self<>((cont, m) -> {
  18.             if (m == 0L)
  19.                 return 1L;
  20.             else
  21.                 return m * cont.func.apply(cont, m - 1);
  22.         });
  23.         return trampoline.func.apply(trampoline, n);
  24.     };
  25.  
  26.     public static void main(String... args) {
  27.          println("factorial(10) = " + factorial.apply(10L));
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement