Advertisement
DulcetAirman

Recursive Functional Interfaces

May 10th, 2015
319
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Usage:
  2. import static com.example.foo.Recursive.*;
  3. // ...
  4. final IntUnaryOperator fib = intUnaryOperator((i, self) -> i <= 1 ? i : self.applyAsInt(i - 1) + self.applyAsInt(i - 2));
  5. for (int n = 0; n <= 10; n++) System.out.format("F%d = %d", n, fib.applyAsInt(n));
  6.  
  7. -------------------------------------------
  8.  
  9. package com.example.foo;
  10.  
  11. import java.util.function.*;
  12.  
  13. public class Recursive<F> {
  14.   private F f;
  15.  
  16.   public static <T, R> Function<T, R> function(final BiFunction<T, Function<T, R>, R> f) {
  17.     final Recursive<Function<T, R>> r = new Recursive<>();
  18.     return r.f = t -> f.apply(t, r.f);
  19.   }
  20.  
  21.   public static IntUnaryOperator intUnaryOperator(final BiFunction<Integer, IntUnaryOperator, Integer> f) {
  22.     final Recursive<IntUnaryOperator> r = new Recursive<>();
  23.     return r.f = i -> f.apply(i, r.f);
  24.   }
  25.  
  26.   public static <R> IntFunction<R> intFunction(final BiFunction<Integer, IntFunction<R>, R> f) {
  27.     final Recursive<IntFunction<R>> r = new Recursive<>();
  28.     return r.f = i -> f.apply(i, r.f);
  29.   }
  30.  
  31.   // TODO : One static method for each interface in java.util.function
  32.  
  33. }
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement