@@ -0,0 +1,1109 @@
+%22%22%22%0AA simple calculator example that implements addition and subtraction.%0A%0ANotice how the more specific pattern is matched.%0A%22%22%22%0A%0Afrom __future__ import print_function, absolute_import%0Afrom alge import datatype, Case, of%0A%0AAdd = datatype(%22Add%22, %5B%22lhs%22, %22rhs%22%5D)%0ASub = datatype(%22Sub%22, %5B%22lhs%22, %22rhs%22%5D)%0ANum = datatype(%22Num%22, %5B%22val%22%5D)%0A%0A%0Aclass calc(Case):%0A    @of(%22Add(Num(a), Num(b))%22)%0A    def add_num(self, a, b):%0A        print(%22add_num%22, self.value)%0A        return a + b%0A%0A    @of(%22Sub(Num(a), Num(b))%22)%0A    def sub_num(self, a, b):%0A        print(%22sub_num%22, self.value)%0A        return a - b%0A%0A    @of(%22Add(a, b)%22)%0A    def add_expr(self, a, b):%0A        print(%22add_expr%22, self.value)%0A        return calc(a) + calc(b)%0A%0A    @of(%22Sub(a, b)%22)%0A    def sub_expr(self, a, b):%0A        print(%22sub_expr%22, self.value)%0A        return calc(a) - calc(b)%0A%0A    @of(%22Num(n)%22)%0A    def num(self, n):%0A        print(%22num%22, self.value)%0A        return n%0A%0A%0Adef main():%0A    expr = Add(Num(1), Sub(Num(3), Num(2)))%0A    result = calc(expr)%0A    print(%22result =%22, result)%0A    assert result == (1 + (3 - 2))%0A%0A%0Aif __name__ == '__main__':%0A    main()%0A

Add calculator example