Commits

Jürgen Bömmels committed 19a17e0

Implement Assoc*-functions

Comments (0)

Files changed (2)

         return W_String(w_char.to_string() * w_number.to_fixnum())
 
 ##
+# Association lists
+## 
+class AssocX(W_Procedure):
+    def procedure(self, ctx, lst):
+        if len(lst) != 2:
+            raise WrongArgsNumber
+
+        (w_obj, w_alst) = lst
+
+        w_iter = w_alst
+        while w_iter is not w_nil:
+            if not isinstance(w_iter, W_Pair):
+                raise WrongArgType(w_alst, "AList")
+
+            w_item = w_iter.car
+
+            if not isinstance(w_item, W_Pair):
+                raise WrongArgType(w_alst, "AList")
+
+            if self.compare(w_obj, w_item.car):
+                return w_item
+
+            w_iter = w_iter.cdr
+
+        return w_false
+
+class Assq(AssocX):
+    _symbol_name = "assq"
+
+    def compare(self, w_obj1, w_obj2):
+        return w_obj1.eq(w_obj2)
+
+class Assv(AssocX):
+    _symbol_name = "assv"
+
+    def compare(self, w_obj1, w_obj2):
+        return w_obj1.eqv(w_obj2)
+
+class Assoc(AssocX):
+    _symbol_name = "assoc"
+
+    def compare(self, w_obj1, w_obj2):
+        return w_obj1.equal(w_obj2)
+
+
+##
 # Equivalnece Predicates
 ##
 class EquivalnecePredicate(W_Procedure):

scheme/test/test_eval.py

     assert eval_noctx("(not #f)").to_boolean()
     assert not eval_noctx("(not '())").to_boolean()
     assert not eval_noctx("(not 0)").to_boolean()
+
+def test_assoc():
+    w_res = eval_noctx("(assq 'b '((a 1) (b 2) (c 3)))")
+    assert isinstance(w_res, W_Pair)
+    assert w_res.equal(parse_("(b 2)"))
+
+    w_res = eval_noctx("(assq 'x '((a 1) (b 2) (c 3)))")
+    assert w_res is w_false
+
+    w_res = eval_noctx("(assv (+ 1 2) '((1 a) (2 b) (3 c)))")
+    assert isinstance(w_res, W_Pair)
+    assert w_res.equal(parse_("(3 c)"))
+
+    w_res = eval_noctx("(assq (list 'a) '(((a)) ((b)) ((c))))")
+    assert w_res is w_false
+
+    w_res = eval_noctx("(assoc (list 'a) '(((a)) ((b)) ((c))))")
+    assert isinstance(w_res, W_Pair)
+    assert w_res.equal(parse_("((a))"))
+
+    w_res = eval_noctx("(assq 'a '())")
+    assert w_res is w_false
+
+    py.test.raises(WrongArgType, eval_noctx, "(assq 'a '(a b c))")
+    py.test.raises(WrongArgType, eval_noctx, "(assq 1 2)")
+    py.test.raises(WrongArgsNumber, eval_noctx, "(assq 1 '(1 2) '(3 4))")
+