Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Result extends Exception {
- public int value;
- public Result(int value) {
- this.value = value;
- }
- }
- abstract class Function {
- abstract public void apply(int input) throws Result;
- public final Function compose(Function other) {
- Function self = this;
- return new Function() {
- public void apply(int input) throws Result {
- try {
- other.apply(input);
- } catch (Result r) {
- self.apply(r.value);
- }
- }
- };
- }
- }
- class Square extends Function {
- public void apply(int x) throws Result {
- throw new Result(x * x);
- }
- }
- class TimesTwo extends Function {
- public void apply(int x) throws Result {
- throw new Result(2 * x);
- }
- }
- class Main {
- public static void main(String[] args) {
- Function f = new Square().compose(new TimesTwo()).compose(new Square());
- try {
- f.apply(2);
- } catch(Result r) {
- System.out.println(r.value);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement