commit b5f18b6adc4966f26e522dc677cdd684c46ad24e
parent efdb67a929094626d7362fd109f5988ee37ba58c
Author: Ed van Bruggen <edvb@uw.edu>
Date: Sun, 29 Dec 2019 01:32:08 -0800
Add list filter function
Diffstat:
2 files changed, 18 insertions(+), 11 deletions(-)
diff --git a/test.c b/test.c
@@ -262,17 +262,18 @@ char *tests[][2] = {
{ "(count 3.2 nil)", "0" },
{ "(count \"Bobandy\" '(1/2 1/4 \"Jim\"))", "0" },
- { "apply", NULL },
- { "(apply list '(1 2 3))", "(1 2 3)" },
- { "(apply + '(2 90))", "92" },
- { "(apply list '(a b c d e))", "(a b c d e)" },
-
- { "map", NULL },
- { "(map car '((1 a) (2 b) (3 c)))", "(1 2 3)" },
- { "(map cdr '((1 a) (2 b) (3 c)))", "((a) (b) (c))" },
- { "(map (lambda (x) (car (cdr x))) '((1 a) (2 b) (3 c)))", "(a b c)" },
- { "(map cadr '((1/2 .5) (\"conky\" .25) ('bubbles .125)))", "(0.5 0.25 0.125)" },
- { "(map inc (list 2 4 8 (^ 2 4)))", "(3 5 9 17)" },
+ { "list proc", NULL },
+ { "(apply list '(1 2 3))", "(1 2 3)" },
+ { "(apply + '(2 90))", "92" },
+ { "(apply list '(a b c d e))", "(a b c d e)" },
+ { "(map car '((1 a) (2 b) (3 c)))", "(1 2 3)" },
+ { "(map cdr '((1 a) (2 b) (3 c)))", "((a) (b) (c))" },
+ { "(map (lambda (x) (car (cdr x))) '((1 a) (2 b) (3 c)))", "(a b c)" },
+ { "(map cadr '((1/2 .5) (\"conky\" .25) ('bubbles .125)))", "(0.5 0.25 0.125)" },
+ { "(map inc (list 2 4 8 (^ 2 4)))", "(3 5 9 17)" },
+ { "(filter positive? '(1 2 -4 5 -9 10))", "(1 2 5 10)" },
+ { "(filter odd? '(8 6 17 9 82 34 27))", "(17 9 27)" },
+ { "(filter integer? '(1/2 3.e-2 9/3 3.2 0.0 8 17))", "(3 8 17)" },
{ "list mod", NULL },
{ "(reverse '(1 2 3 4 5))", "(5 4 3 2 1)" },
diff --git a/tibs/lib.tsp b/tibs/lib.tsp
@@ -147,6 +147,12 @@
(map proc (cdr lst)))
nil))
+(define (filter proc lst)
+ (cond
+ ((not (pair? lst)) nil)
+ ((proc (car lst)) (cons (car lst) (filter proc (cdr lst))))
+ (else (filter proc (cdr lst)))))
+
(define (reverse l)
(recur f ((in l) (out nil))
(if (pair? in)