浏览代码

generate_line now rewrites 'a + -b' to 'a - b'.

Taddeus Kroes 14 年之前
父节点
当前提交
8692113740
共有 2 个文件被更改,包括 11 次插入1 次删除
  1. 7 1
      line.py
  2. 4 0
      tests/test_line.py

+ 7 - 1
line.py

@@ -103,8 +103,8 @@ def generate_line(root):
 
                     e.append(exp)
 
-                # Check if a multiplication sign is nessecary
                 if op == '*':
+                    # Check if an explicit multiplication sign is nessecary
                     left, right = node
 
                     # Get the previous multiplication element if the arity is
@@ -127,6 +127,12 @@ def generate_line(root):
                     if (left_id or left_paren or left_int) \
                             and (right_id or right_paren):
                         sep = ''
+                elif op == '+':
+                    # An addition with negation can be written as a
+                    # subtraction, e.g. 1 + -2 == 1 - 2
+                    if node[1].title() == '-' and len(node[1]) == 1:
+                        sep = ' - '
+                        e[1] = e[1][1:]
 
                 result += sep.join(e)
         else:

+ 4 - 0
tests/test_line.py

@@ -122,3 +122,7 @@ class TestLine(unittest.TestCase):
         self.assertEquals(generate_line(mul), '2a')
         mul = N('*', a, l2)
         self.assertEquals(generate_line(mul), 'a * 2')
+
+    def test_plus_to_minus(self):
+        plus = N('+', L(1), N('-', L(2)))
+        self.assertEquals(generate_line(plus), '1 - 2')