Advertisement
Guest User

Test

a guest
Feb 20th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. class Result extends Exception {
  2.     public int value;
  3.     public Result(int value) {
  4.         this.value = value;
  5.     }
  6. }
  7.  
  8. abstract class Function {
  9.     abstract public void apply(int input) throws Result;
  10.     public final Function compose(Function other) {
  11.         Function self = this;
  12.         return new Function() {
  13.             public void apply(int input) throws Result {
  14.                 try {
  15.                     other.apply(input);
  16.                 } catch (Result r) {
  17.                     self.apply(r.value);
  18.                 }
  19.             }
  20.         };
  21.     }
  22. }
  23.  
  24. class Square extends Function {
  25.     public void apply(int x) throws Result {
  26.         throw new Result(x * x);
  27.     }
  28. }
  29.  
  30. class TimesTwo extends Function {
  31.     public void apply(int x) throws Result {
  32.         throw new Result(2 * x);
  33.     }
  34. }
  35.  
  36. class Main {
  37.   public static void main(String[] args) {
  38.     Function f = new Square().compose(new TimesTwo()).compose(new Square());
  39.     try {
  40.       f.apply(2);
  41.     } catch(Result r) {
  42.       System.out.println(r.value);
  43.     }
  44.   }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement