From f72ff53f4177a877fa697f6f5242a9f74cba80db Mon Sep 17 00:00:00 2001 From: Abhishek L Date: Sun, 15 Dec 2013 11:42:57 +0530 Subject: [PATCH] Operators + and * work without args, fixes #372 Like other lisps, operators `+` and `*` return their identity values when called with no arguments. Also with a single operand they return the operand. This fixes #372 --- hy/compiler.py | 19 +++++++++++++++++-- tests/native_tests/math.hy | 8 ++++++-- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/hy/compiler.py b/hy/compiler.py index 67918e0..cd50fa6 100644 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -1343,11 +1343,9 @@ class HyASTCompiler(object): lineno=e.start_line, col_offset=e.start_column) - @builds("+") @builds("%") @builds("/") @builds("//") - @builds("*") @builds("**") @builds("<<") @builds(">>") @@ -1384,6 +1382,23 @@ class HyASTCompiler(object): col_offset=child.start_column) return ret + @builds("+") + @builds("*") + def compile_maths_expression_mul(self, expression): + if len(expression) > 2: + return self.compile_maths_expression(expression) + else: + id_op = {"+": HyInteger(0), "*": HyInteger(1)} + + op = expression.pop(0) + arg = expression.pop(0) if expression else id_op[op] + expr = HyExpression([ + HySymbol(op), + id_op[op], + arg + ]).replace(expression) + return self.compile_maths_expression(expr) + @builds("-") @checkargs(min=1) def compile_maths_expression_sub(self, expression): diff --git a/tests/native_tests/math.hy b/tests/native_tests/math.hy index eda77b0..0824876 100644 --- a/tests/native_tests/math.hy +++ b/tests/native_tests/math.hy @@ -8,7 +8,9 @@ (setv test_mult (fn [] "NATIVE: Test multiplication." - (assert (= 4 (square 2))))) + (assert (= 4 (square 2))) + (assert (= 8 (* 8))) + (assert (= 1 (*))))) (setv test_sub (fn [] @@ -19,7 +21,9 @@ (setv test_add (fn [] "NATIVE: Test addition" - (assert (= 4 (+ 1 1 1 1))))) + (assert (= 4 (+ 1 1 1 1))) + (assert (= 8 (+ 8))) + (assert (= 0 (+))))) (setv test_div (fn []