我正在制作最终明天的练习单,我有点困惑,想弄清楚问题是什么以及如何解决它。我想在这里查看,看看堆栈溢出的好人是否可以帮我解决它。
问题设置如下:
显示派生树(这是一个类型检查的痕迹),证明以下表达式具有类型:
(appC (lamC ‘x ??? (plusC (idC ‘x) (numC 1)))
(numC 2) )
它基于类型检查的这个定义:
(define (typecheck [a : ExprC] [tenv : TypeEnv])
(type-case ExprC a
[numC (n) (numT)]
[plusC (l r) (typecheck-nums l r tenv)]
[multC (l r) (typecheck-nums l r tenv)]
[idC (n) (type-lookup n tenv)]
[lamC (n arg-type body)
(arrowT arg-type
(typecheck body
(extend-env (tbind n arg-type)
tenv)))]
[appC (fun arg)
(type-case Type (typecheck fun tenv)
[arrowT (arg-type result-type)
(if (equal? arg-type
(typecheck arg tenv))
result-type
(type-error arg
(to-string arg-type)))]
[else (type-error fun "function")])]))
(define (typecheck-nums l r tenv)
(type-case Type (typecheck l tenv)
[numT ()
(type-case Type (typecheck r tenv)
[numT () (numT)]
[else (type-error r "num")])]
[else (type-error l "num")]))
(define (type-error a msg)
(error 'typecheck (string-append
"no type: "
(string-append
(to-string a)
(string-append " not "
msg)))))
当我在球拍中运行时:
(typecheck (appC
(lamC 'x (numT) (plusC (idC 'x) (numC 1)))
(numC 2))
mt-env)
我明白了:
- Type
(numT)
- Type
(numT)
在底部说明:
"您检查' x的类型必须是:numT"
所以它提出了numT但是我对跟踪部分感到困惑,我知道这个问题很长,但这是所有让我最困惑的练习题中的一个。任何建议/帮助表示赞赏
答案 0 :(得分:0)
问题:“显示派生树,证明以下表达式具有类型”意味着您需要证明表达式具有给定类型。
考虑这个例子(与你的类型检查示例无关):
评估表达式(+ 1 2)
的结果具有类型int
。
原因:
The subexpression 1 has type int
The subexpression 2 has type int
The subexpression + has type int int -> int
由于应用程序规则的上述类型,所以 应用int int类型的函数 - > int到int类型的两个参数,结果类型为int。
类型检查器递归地检查表达式。它首先确定子表达式的类型,然后使用它们的类型来推断复合表达式的类型。
为了获得给定表达式具有特定类型的证据,可以使用运行类型检查器的跟踪。要获取跟踪,请修改typechecker以在推断时打印类型。
未经测试的修改:
(define (typecheck [a : ExprC] [tenv : TypeEnv])
(define (tell result-type)
(display "The type of ")
(display a)
(display " is: ")
(display result-type)
(newline))
(tell
(type-case ExprC a
[numC (n) (numT)]
[plusC (l r) (typecheck-nums l r tenv)]
[multC (l r) (typecheck-nums l r tenv)]
[idC (n) (type-lookup n tenv)]
[lamC (n arg-type body) (arrowT arg-type
(typecheck body
(extend-env (tbind n arg-type)
tenv)))]
[appC (fun arg) (type-case Type (typecheck fun tenv)
[arrowT (arg-type result-type)
(if (equal? arg-type
(typecheck arg tenv))
result-type
(type-error arg
(to-string arg-type)))]
[else (type-error fun "function")])])))