Commits

Jürgen Bömmels committed d86450b

Turn W_Nil and W_Boolean into singleton classes

Comments (0)

Files changed (3)

 w_ellipsis = symbol("...")
 
 class W_Boolean(W_Root):
+    def __new__(cls, val):
+        if val:
+            return w_true
+        else:
+            return w_false
+
     def __init__(self, val):
-        self.boolval = bool(val)
+        pass
+            
+class W_True(W_Boolean):
+    _w_true = None
+    def __new__(cls, val):
+        if cls._w_true is None:
+            cls._w_true = W_Root.__new__(cls)
+        return cls._w_true
+
+    def __init__(self, val):
+        assert val
 
     def to_repr(self):
-        if self.boolval:
-            return "#t"
+        return "#t"
+    to_string = to_repr
+
+w_true = W_True(True)
+
+class W_False(W_Boolean):
+    _w_false = None
+    def __new__(cls, val):
+        if cls._w_false is None:
+            cls._w_false = W_Root.__new__(cls)
+        return cls._w_false
+
+    def __init__(self, val):
+        assert not val
+
+    def to_repr(self):
         return "#f"
-
     to_string = to_repr
 
     def to_boolean(self):
-        return self.boolval
+        return False
 
-    def eqv(self, w_obj):
-        if isinstance(w_obj, W_Boolean):
-            return self.boolval is w_obj.boolval
-        return False
-    eq = eqv
-    equal = eqv
+w_false = W_False(False)
 
 class W_String(W_Root):
     def __init__(self, val):
     pass
 
 class W_Nil(W_List):
+    _w_nil = None
+    def __new__(cls):
+        if cls._w_nil is None:
+            cls._w_nil = W_Root.__new__(cls)
+        return cls._w_nil
+    
     def __repr__(self):
         return "<W_Nil ()>"
 

scheme/test/test_object.py

     w_nil = W_Nil()
     assert w_nil.to_boolean() is True # this is Scheme not LISP
     assert w_nil.to_repr() == "()"
+    w_nil2 = W_Nil()
+    assert w_nil is w_nil2
 
 def test_pair():
     c1 = W_Integer(1)

scheme/test/test_parser.py

     elif isinstance(w_obj, W_Character):
         return w_obj.chrval
     elif isinstance(w_obj, W_Boolean):
-        return w_obj.boolval
+        return w_obj.to_boolean()
     elif isinstance(w_obj, W_Pair):
         result = []
         while not isinstance(w_obj, W_Nil):