Built-in rules are now more stable. Defining and undefining rules is now possible.
authorimode <immediate.mode@gmail.com>
Tue, 13 Nov 2018 05:25:04 +0000 (21:25 -0800)
committerimode <immediate.mode@gmail.com>
Tue, 13 Nov 2018 05:25:04 +0000 (21:25 -0800)
modal.py

index 521dbc1..443fcf9 100644 (file)
--- a/modal.py
+++ b/modal.py
@@ -92,6 +92,32 @@ def apply(queue, rules, pattern, replacement):
         return dequeue(queue, len(pattern));
     return enqueue(dequeue(queue, len(pattern)), replacement);
 
+def define(queue, rules, pattern):
+    context = match(pattern, queue);
+    left    = context["left"];
+    right   = context["right"];
+    if right and left:
+        if len(left) > 1:
+            left = left[1:][:-1];
+        if len(right) > 1:
+            right = right[1:][:-1];
+        rules.append(rule(left, right));
+        return dequeue(queue, len(construct(pattern, context)));
+    return queue;
+
+def undefine(queue, rules, pattern):
+    context = match(pattern, queue);
+    left    = context["left"];
+    if left:
+        if len(left) > 1:
+            left = left[1:][:-1];
+        for rule, index in zip(rules, range(0, len(rules))):
+            candidate , _, _ = rule;
+            if candidate == left:
+                del rules[index];
+        return dequeue(queue, len(construct(pattern, context)));
+    return queue;
+
 def applicable(rules, queue):
     results = [];
     for pattern, operation, parameters in rules:
@@ -223,16 +249,10 @@ def help():
     print(prefix + "help  : This message.");
     print(prefix + "quit  : Quit.");
 
-def defrule(queue, rules, pattern):
-    context = match(pattern, queue);
-    if "left" in context.keys() and "right" in context.keys():
-        rules.append(rule(context["left"], context["right"]));
-        return dequeue(queue, len(construct(pattern, context)));
-    return queue;
-
 def main():
     builtins = [
-                    (parse("def ?left ?right"), defrule, [])
+                    (parse("define ?left ?right"), define,   []),
+                    (parse("undefine ?left"),      undefine, [])
                ];
     if len(sys.argv) >= 2:
         content = read(sys.argv[1]);