Add ast-find
authorLuke Lau <luke_lau@icloud.com>
Mon, 29 Jul 2019 12:44:23 +0000 (13:44 +0100)
committerLuke Lau <luke_lau@icloud.com>
Mon, 29 Jul 2019 12:44:23 +0000 (13:44 +0100)
ast.scm

diff --git a/ast.scm b/ast.scm
index a38a01257aea179e4638d376400fcc77e1c9318e..2beb94507572eafd20b586d2ce9ef3867ec63d3e 100644 (file)
--- a/ast.scm
+++ b/ast.scm
                 (fold-map inner (cdr x)))]
     [else (f x)]))
 
+(define (ast-find p x)
+  (define (inner y) (ast-find p y))
+  (define (any p x) (fold-left
+                    (lambda (acc y) (if acc #t (p y)))
+                    #f
+                    x))
+  (define (either . fs)
+    (if (null? fs) #f
+       (if (car fs) (car fs)
+           (apply either (cdr fs)))))
+                    
+  (case (ast-type x)
+    ['let (either (p x)
+                 (any inner (let-bindings x))
+                 (any inner (let-body x)))]
+    ['app (either (p x)
+                 (any inner x))]
+    ['lambda (either (p x)
+                    (inner (lambda-body x)))]
+    ['if (either (p x) (any inner (cdr x)))]
+    [else (p x)]))
+
 (define let-bindings cadr)
 (define let-body cddr)