; we typecheck the lambda calculus only (only single arg lambdas)
(define (typecheck prog)
(define (check env x)
- (display "check: ")
- (display x)
- (display "\n\t")
- (display env)
- (newline)
+ ;; (display "check: ")
+ ;; (display x)
+ ;; (display "\n\t")
+ ;; (display env)
+ ;; (newline)
(let
((res
(cond
((lambda? x)
(let* ((new-env (env-insert env (lambda-arg x) (fresh-tvar)))
(body-type-res (check new-env (lambda-body x)))
- (subd-env (substitute-env (car body-type-res) new-env)))
- (display "lambda: ")
- (display body-type-res)
- (display "\n")
- (display subd-env)
- (display "\n")
+ (cs (car body-type-res))
+ (subd-env (substitute-env (car body-type-res) new-env))
+ (arg-type (env-lookup subd-env (lambda-arg x)))
+ (resolved-arg-type (substitute cs arg-type)))
+ ;; (display "lambda:\n\t")
+ ;; (display prog)
+ ;; (display "\n\t")
+ ;; (display cs)
+ ;; (display "\n\t")
+ ;; (display resolved-arg-type)
+ ;; (newline)
(list (car body-type-res)
(list 'abs
- (env-lookup subd-env (lambda-arg x))
+ resolved-arg-type
(cadr body-type-res)))))
((app? x) ; (f a)
(list 'abs
arg-type
(fresh-tvar))))
- (cs (append func-c (car arg-type-res) (car func-type-res)))
+ (cs (consolidate
+ (consolidate func-c (car arg-type-res))
+ (car func-type-res)))
(resolved-func-type (substitute cs func-type))
(resolved-return-type (caddr resolved-func-type)))
(let ((return-type (substitute cs (caddr resolved-func-type))))
(list cs return-type))
(error #f "not a function")))))))
- (display "result of ")
- (display x)
- (display ":\n\t")
- (display (cadr res))
- (display "[")
- (display (car res))
- (display "]\n")
+ ;; (display "result of ")
+ ;; (display x)
+ ;; (display ":\n\t")
+ ;; (display (cadr res))
+ ;; (display "[")
+ ;; (display (car res))
+ ;; (display "]\n")
res))
(cadr (check '() (normalize prog))))
(unify (caddr a) (caddr b))))
(else (error #f "could not unify"))))
-
; TODO: what's the most appropriate substitution?
; should all constraints just be limited to a pair?
(define (substitute cs t)
; gets the first concrete type
; otherwise returns the last type variable
+
(define (get-concrete c)
- (if (null? (cdr c))
- (car c)
+ (let ((last (null? (cdr c))))
(if (not (tvar? (car c)))
+ (if (abs? (car c))
+ (substitute cs (car c))
+ (car c))
+ (if last
(car c)
- (get-concrete (cdr c)))))
+ (get-concrete (cdr c))))))
+ (cond
+ ((abs? t) (list 'abs
+ (substitute cs (cadr t))
+ (substitute cs (caddr t))))
+ (else
(fold-left
(lambda (t c)
(if (member t c)
(get-concrete c)
t))
- t cs))
+ t cs))))
(define (substitute-env cs env)
(map (lambda (x) (cons (car x) (substitute cs (cdr x)))) env))