X-Git-Url: http://git.lukelau.me/?p=scheme.git;a=blobdiff_plain;f=ast.scm;h=5064ca554bc8033bdbc0b483ac79249cd3312f73;hp=469a96f7162cb09c77dac0ed71b971dcbbd179a0;hb=844dcd052c6f551d9936693c2b4c49cf920c7051;hpb=a64f7097fa246c19a4c69d0aad65e60378273887 diff --git a/ast.scm b/ast.scm index 469a96f..5064ca5 100644 --- a/ast.scm +++ b/ast.scm @@ -71,8 +71,16 @@ [else (p x)])) (define (let-bindings e) - (define (extract x) ) ; TODO - (flat-map extract (cadr e)) + (define (pattern-match x body) + (if (eqv? (ast-type x) 'var) + (list (cons x body)) + (let* ([constructor (car x)] + [destructor (lambda (i) (dtor-name constructor i))]) + (flat-map (lambda (y i) + (pattern-match y (list (destructor i) body))) + (cdr x) + (range 0 (length (cdr x))))))) + (flat-map (lambda (x) (pattern-match (car x) (cdr x))) (cadr e))) (define let-body cddr) (define (lambda? x) @@ -100,6 +108,48 @@ ,@(filter (lambda (x) (eqv? (statement-type x) 'expr)) program))) + ; gets both constructors and destructors + ; (data A (foo Int Bool) + ; (bar Bool)) + ; | + ; v + ; (foo . (abs Int (abs Bool A))) + ; (foo~0 . (abs A Int) + ; (foo~1 . (abs A Bool) + ; (bar . (abs Bool A) + ; (bar~0 . (abs A Bool) + +(define (data-tors data-def) + (define (constructor-type t products) + (fold-right (lambda (x acc) `(abs ,x ,acc)) t products)) + + (define (destructor ctor-name prod-type part-type index) + (let ([name (dtor-name ctor-name index)]) + (cons name `(abs ,prod-type ,part-type)))) + + (let ([type-name (cadr data-def)] + [ctors (cddr data-def)]) + (fold-right + (lambda (ctor acc) + (let* ([ctor-name (car ctor)] + [products (cdr ctor)] + + [maker (cons ctor-name (constructor-type type-name products))] + + [dtors (map (lambda (t i) (destructor ctor-name type-name t i)) + products + (range 0 (length products)))]) + + (cons maker (append dtors acc)))) + '() + ctrs))) + +(define (dtor-name ctor-name index) + (string->symbol + (string-append (symbol->string ctor-name) + "~" + (number->string index)))) + ; for use in normalized form (define lambda-arg caadr) ; for use elsewhere @@ -107,7 +157,12 @@ (define lambda-body caddr) ; utils -(define (flat-map f x) (fold-left append '() (map f x))) +(define (range s n) + (if (= 0 n) '() + (append (range s (- n 1)) + (list (+ s (- n 1)))))) + +(define (flat-map f . xs) (fold-left append '() (apply map (cons f xs)))) (define (repeat x n) (if (<= n 0) '() (cons x (repeat x (- n 1)))))