Created
February 18, 2011 14:09
-
-
Save chanwit/833690 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // Actually, its filename is Test.gpp | |
| // | |
| class Test { | |
| static class Expr<T> { | |
| } | |
| static class Bin<T> extends Expr<T> { | |
| Expr<T> op1 | |
| Expr<T> op2 | |
| } | |
| static class Const<T> extends Expr<T> { | |
| T val | |
| } | |
| static class Plus<T> extends Bin<T> { | |
| } | |
| static class Mult<T> extends Bin<T> { | |
| } | |
| @mixed static setup() { | |
| Integer.metaClass.plus = { Integer op -> | |
| Integer op1 = delegate | |
| Integer op2 = op | |
| new Plus<Integer>(op1: new Const<Integer>(val:op1), op2: new Const<Integer>(val:op2)) | |
| } | |
| Integer.metaClass.multiply = { Integer op -> | |
| Integer op1 = delegate | |
| Integer op2 = op | |
| new Mult<Integer>(op1: new Const<Integer>(val:op1), op2: new Const<Integer>(val:op2)) | |
| } | |
| } | |
| static match(Expr a, Expr b) { | |
| return [a.class, b.class] | |
| } | |
| static Expr optimize(Mult e) { | |
| if (match(e.op1, e.op2) == [Const, Const]) | |
| return new Const<Integer>(val: (e.op1 as Const<Integer>).val * (e.op2 as Const<Integer>).val) | |
| if((e.op1 as Const).val == 1) return (e.op2 as Const) else | |
| if((e.op2 as Const).val == 1) return (e.op1 as Const) | |
| } | |
| @dynamic static void main(String[] args) { | |
| setup() | |
| def a = 1 * 2 | |
| println optimize(a).val | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment