在OCaml中使用GADTs构建简单的lambda演算DSL

11
如何使用GADTs在OCaml中定义类似于简单lambda演算的DSL?具体而言,我无法弄清楚如何正确地定义类型检查器,以将未打标签的AST转换为已打标签的AST,也无法弄清楚上下文和环境的正确类型。
以下是使用传统方法在OCaml中实现简单lambda演算语言的一些代码。
(* Here's a traditional implementation of a lambda calculus like language *)

type typ =
| Boolean
| Integer
| Arrow of typ*typ

type exp =
| Add of exp*exp
| And of exp*exp
| App of exp*exp
| Lam of string*typ*exp
| Var of string
| Int of int
| Bol of bool

let e1=Add(Int 1,Add(Int 2,Int 3))
let e2=Add(Int 1,Add(Int 2,Bol false)) (* Type error *)
let e3=App(Lam("x",Integer,Add(Var "x",Var "x")),Int 4)

let rec typecheck con e =
    match e with
    | Add(e1,e2) ->
        let t1=typecheck con e1 in
        let t2=typecheck con e2 in
        begin match (t1,t2) with 
        | (Integer,Integer) -> Integer
        | _ -> failwith "Tried to add with something other than Integers"
        end
    | And(e1,e2) ->
        let t1=typecheck con e1 in
        let t2=typecheck con e2 in
        begin match (t1,t2) with 
        | (Boolean,Boolean) -> Boolean 
        | _ -> failwith "Tried to and with something other than Booleans"
        end
    | App(e1,e2) ->
        let t1=typecheck con e1 in
        let t2=typecheck con e2 in
        begin match t1 with 
        | Arrow(t11,t12) ->
            if t11 <> t2 then
                failwith "Mismatch of types on a function application"
            else
                t12
        | _ -> failwith "Tried to apply a non-arrow type" 
        end
    | Lam(x,t,e) ->
        Arrow (t,typecheck ((x,t)::con) e)
    | Var x  ->
        let (y,t) = List.find (fun (y,t)->y=x) con in
        t
    | Int _ -> Integer
    | Bol _ -> Boolean

let t1 = typecheck [] e1
(* let t2 = typecheck [] e2 *)
let t3 = typecheck [] e3

type value = 
| VBoolean of bool
| VInteger of int
| VArrow of ((string*value) list -> value -> value)

let rec eval env e = 
    match e with
    | Add(e1,e2) ->
        let v1=eval env e1 in
        let v2=eval env e2 in
        begin match (v1,v2) with 
        | (VInteger i1,VInteger i2) -> VInteger (i1+i2) 
        | _ -> failwith "Tried to add with something other than Integers"
        end
    | And(e1,e2) ->
        let v1=eval env e1 in
        let v2=eval env e2 in
        begin match (v1,v2) with 
        | (VBoolean b1,VBoolean b2) -> VBoolean (b1 && b2) 
        | _ -> failwith "Tried to and with something other than Booleans"
        end
    | App(e1,e2) ->
        let v1=eval env e1 in
        let v2=eval env e2 in
        begin match v1 with 
        | VArrow a1 -> a1  env v2 
        | _ -> failwith "Tried to apply a non-arrow type" 
        end
    | Lam(x,t,e) ->
        VArrow (fun env' v' -> eval ((x,v')::env') e) 
    | Var x  ->
        let (y,v) = List.find (fun (y,t)->y=x) env in
        v 
    | Int i -> VInteger i 
    | Bol b -> VBoolean b

let v1 = eval [] e1
let v3 = eval [] e3

现在,我正在尝试将这个内容翻译为使用GADTs的形式。以下是我的开端:

(* Now, we try to GADT the process *) 

type exp =
| Add of exp*exp
| And of exp*exp
| App of exp*exp
| Lam of string*typ*exp
| Var of string
| Int of int
| Bol of bool

let e1=Add(Int 1,Add(Int 2,Int 3))
let e2=Add(Int 1,Add(Int 2,Bol false))
let e3=App(Lam("x",Integer,Add(Var "x",Var "x")),Int 4)

type _ texp =
| TAdd : int texp * int texp -> int texp
| TAnd : bool texp * bool texp -> bool texp
| TApp : ('a -> 'b) texp * 'a texp -> 'b texp
| TLam : string*'b texp -> ('a -> 'b) texp
| TVar : string -> 'a texp
| TInt : int -> int texp
| TBol : bool -> bool texp

let te1 = TAdd(TInt 1,TAdd(TInt 2,TInt 3))

let rec typecheck : type a. exp -> a texp = fun e ->
    match e with
    | Add(e1,e2) ->
        let te1 = typecheck e1 in
        let te2 = typecheck e2 in
        TAdd (te1,te2)
    | _ -> failwith "todo"

以下是问题。首先,我不确定如何为texp类型中的TLam和TVar定义正确的类型。通常,我会提供变量名称的类型,但我不确定在此上下文中如何实现。其次,我不知道函数typecheck中上下文的正确类型。以前,我使用了某种列表,但现在我不确定列表的类型。第三,在省略上下文之后,typecheck函数本身无法进行类型检查。它会失败并显示以下消息:

File "test03.ml", line 32, characters 8-22:
Error: This expression has type int texp
       but an expression was expected of type a texp
       Type int is not compatible with type a 

这完全是有道理的。问题在于我不确定typecheck的正确类型是什么。

无论如何,你怎么修复这些函数呢?


编辑1

这里是上下文或环境的可能类型。

type _ ctx =
| Empty : unit ctx
| Item :  string * 'a * 'b ctx -> ('a*'b) ctx

编辑2

环境的技巧在于确保环境的类型嵌入到表达式的类型中。否则,没有足够的信息来保证类型安全。这是一个完成的解释器。目前,我还没有有效的类型检查器来从未经类型标记的表达式转换为经过类型标记的表达式。

type (_,_) texp =
| TAdd : ('e,int) texp * ('e,int) texp -> ('e,int) texp
| TAnd : ('e,bool) texp * ('e,bool) texp -> ('e,bool) texp
| TApp : ('e,('a -> 'b)) texp * ('e,'a) texp -> ('e,'b) texp
| TLam : (('a*'e),'b) texp -> ('e,('a -> 'b)) texp
| TVar0 : (('a*'e),'a) texp
| TVarS : ('e,'a) texp -> (('b*'e),'a) texp
| TInt : int -> ('e,int) texp
| TBol : bool -> ('e,bool) texp

let te1 = TAdd(TInt 1,TAdd(TInt 2,TInt 3))
(*let te2 = TAdd(TInt 1,TAdd(TInt 2,TBol false))*)
let te3 = TApp(TLam(TAdd(TVar0,TVar0)),TInt 4)
let te4 = TApp(TApp(TLam(TLam(TAdd(TVar0,TVarS(TVar0)))),TInt 4),TInt 5)
let te5 = TLam(TLam(TVarS(TVar0)))

let rec eval : type e t. e -> (e,t) texp -> t = fun env e -> 
    match e with
    | TAdd (e1,e2) ->
        let v1 = eval env e1 in
        let v2 = eval env e2 in
        v1 + v2
    | TAnd (e1,e2) ->
        let v1 = eval env e1 in
        let v2 = eval env e2 in
        v1 && v2
    | TApp (e1,e2) ->
        let v1 = eval env e1 in
        let v2 = eval env e2 in
        v1 v2
    | TLam e ->
        fun x -> eval (x,env) e 
    | TVar0 ->
        let (v,vs)=env in
        v
    | TVarS e ->
        let (v,vs)=env in
        eval vs e 
    | TInt i -> i
    | TBol b -> b

然后,我们有

# eval () te1;;
- : int = 6
# eval () te3;;
- : int = 8
# eval () te5;;
- : '_a -> '_b -> '_a = <fun>
# eval () te4;;
- : int = 9

你应该看一下这篇论文 - gallais
从这个问题中,我尝试完全实现了一个lambda演算,并将ADT转换为GADT。我主要遵循[@gasche][^1]的链接,这是结果。它有点庞大,但你可以处理递归(仅适用于尾递归函数)和原语。享受吧![^1]: https://github.com/shayan-najd/MiniFeldspar/tree/master/Philip - Romain Calascibetta
2个回答

8
如果您希望术语表示执行良好的类型检查,您需要更改类型环境(和变量)的表示方式:您不能很好地对从字符串到值的映射进行细分类型(用于表示映射的类型是同质的)。经典解决方案是使用De Bruijn指数(强类型数字)而不是变量名来表示变量。在未打上类型标记的世界中进行转换可能会有所帮助,然后只关心未打上类型标记 -> GADT传递中的类型检查。
以下是粗略草图的强类型变量的GADT声明:
type (_, _) var =
  | Z : ('a, 'a * 'g) var
  | S : ('a, 'g) var -> ('a, 'b * 'g) var

('a, 'g) var 类型的值应该被理解为一种从类型为 'g 的环境中提取类型为 'a 的值的方式的描述。环境由一个右嵌套元组级联表示。 Z 案例对应于选择环境中的第一个变量,而 S 案例忽略顶部变量并深入查找环境。

Shayan Najd 实现了这个想法(使用 Haskell),可以在 github 上查看。随意查看 GADT 表示类型检查/翻译代码


4

好的,我终于理清了。由于可能不只有我发现这很有趣,所以这里是一组完整的代码,既可以进行类型检查,又可以进行评估:

type (_,_) texp =
| TAdd : ('gamma,int) texp * ('gamma,int) texp -> ('gamma,int) texp
| TAnd : ('gamma,bool) texp * ('gamma,bool) texp -> ('gamma,bool) texp
| TApp : ('gamma,('t1 -> 't2)) texp * ('gamma,'t1) texp -> ('gamma,'t2) texp
| TLam : (('gamma*'t1),'t2) texp -> ('gamma,('t1 -> 't2)) texp
| TVar0 : (('gamma*'t),'t) texp
| TVarS : ('gamma,'t1) texp -> (('gamma*'t2),'t1) texp
| TInt : int -> ('gamma,int) texp
| TBol : bool -> ('gamma,bool) texp

type _ typ =
| Integer : int typ
| Boolean : bool typ
| Arrow : 'a typ * 'b typ -> ('a -> 'b) typ

type (_,_) iseq = IsEqual : ('a,'a) iseq
let rec is_equal : type a b. a typ -> b typ -> (a,b) iseq option = fun a b ->
    match a, b with
    | Integer, Integer -> Some IsEqual
    | Boolean, Boolean -> Some IsEqual
    | Arrow(t1,t2), Arrow(u1,u2) ->
        begin match is_equal t1 u1, is_equal t2 u2 with
        | Some IsEqual, Some IsEqual -> Some IsEqual
        | _ -> None
        end
    | _ -> None

type _ isint = IsInt : int isint
let is_integer : type a. a typ -> a isint option = fun a -> 
    match a with
    | Integer -> Some IsInt
    | _ -> None

type _ isbool = IsBool : bool isbool
let is_boolean : type a. a typ -> a isbool option = fun a -> 
    match a with
    | Boolean -> Some IsBool 
    | _ -> None

type _ context =
| CEmpty : unit context 
| CVar : 'a context * 't typ -> ('a*'t) context 

type exp =
| Add of exp*exp
| And of exp*exp
| App of exp*exp
| Lam : 'a typ * exp -> exp
| Var0
| VarS of exp
| Int of int
| Bol of bool

type _ exists_texp =
| Exists : ('gamma,'t) texp * 't typ -> 'gamma exists_texp

let rec typecheck
    : type gamma t. gamma context -> exp -> gamma exists_texp =
fun ctx e ->
    match e with
    | Int i -> Exists ((TInt i) , Integer)
    | Bol b -> Exists ((TBol b) , Boolean)
    | Var0 ->
        begin match ctx with
        | CEmpty -> failwith "Tried to grab a nonexistent variable"
        | CVar(ctx,t) -> Exists (TVar0 , t)
        end
    | VarS e ->
        begin match ctx with
        | CEmpty -> failwith "Tried to grab a nonexistent variable"
        | CVar(ctx,_) ->
            let tet = typecheck ctx e in
            begin match tet with
            | Exists (te,t) -> Exists ((TVarS te) , t)
            end
        end
    | Lam(t1,e) ->
        let tet2 = typecheck (CVar (ctx,t1)) e in
        begin match tet2 with
        | Exists (te,t2) -> Exists ((TLam te) , (Arrow(t1,t2)))
        end
    | App(e1,e2) ->
        let te1t1 = typecheck ctx e1 in
        let te2t2 = typecheck ctx e2 in
        begin match te1t1,te2t2 with
        | Exists (te1,t1),Exists (te2,t2) ->
            begin match t1 with
            | Arrow(t11,t12) ->
                let p = is_equal t11 t2 in
                begin match p with
                | Some IsEqual -> 
                    Exists ((TApp (te1,te2)) , t12)
                | None -> 
                    failwith "Mismatch of types on a function application"
                end
            | _ -> failwith "Tried to apply a non-arrow type" 
            end
        end
    | Add(e1,e2) ->
        let te1t1 = typecheck ctx e1 in
        let te2t2 = typecheck ctx e2 in
        begin match te1t1,te2t2 with
        | Exists (te1,t1),Exists (te2,t2) ->
            let p = is_equal t1 t2 in
            let q = is_integer t1 in
            begin match p,q with
            | Some IsEqual, Some IsInt ->
                Exists ((TAdd (te1,te2)) , t1)
            | _ ->
                failwith "Tried to add with something other than Integers"
            end
        end
    | And(e1,e2) ->
        let te1t1 = typecheck ctx e1 in
        let te2t2 = typecheck ctx e2 in
        begin match te1t1,te2t2 with
        | Exists (te1,t1),Exists (te2,t2) ->
            let p = is_equal t1 t2 in
            let q = is_boolean t1 in
            begin match p,q with
            | Some IsEqual, Some IsBool ->
                Exists ((TAnd (te1,te2)) , t1)
            | _ ->
                failwith "Tried to and with something other than Booleans"
            end
        end

let e1 = Add(Int 1,Add(Int 2,Int 3))
let e2 = Add(Int 1,Add(Int 2,Bol false))
let e3 = App(Lam(Integer,Add(Var0,Var0)),Int 4)
let e4 = App(App(Lam(Integer,Lam(Integer,Add(Var0,VarS(Var0)))),Int 4),Int 5)
let e5 = Lam(Integer,Lam(Integer,VarS(Var0)))
let e6 = App(Lam(Integer,Var0),Int 1)
let e7 = App(Lam(Integer,Lam(Integer,Var0)),Int 1)
let e8 = Lam(Integer,Var0)
let e9 = Lam(Integer,Lam(Integer,Var0))

let tet1 = typecheck CEmpty e1
(*let tet2 = typecheck CEmpty e2*)
let tet3 = typecheck CEmpty e3
let tet4 = typecheck CEmpty e4
let tet5 = typecheck CEmpty e5
let tet6 = typecheck CEmpty e6
let tet7 = typecheck CEmpty e7
let tet8 = typecheck CEmpty e8
let tet9 = typecheck CEmpty e9

let rec eval : type gamma t. gamma -> (gamma,t) texp -> t = fun env e -> 
    match e with
    | TAdd (e1,e2) ->
        let v1 = eval env e1 in
        let v2 = eval env e2 in
        v1 + v2
    | TAnd (e1,e2) ->
        let v1 = eval env e1 in
        let v2 = eval env e2 in
        v1 && v2
    | TApp (e1,e2) ->
        let v1 = eval env e1 in
        let v2 = eval env e2 in
        v1 v2
    | TLam e ->
        fun x -> eval (env,x) e 
    | TVar0 ->
        let (env,x)=env in
        x
    | TVarS e ->
        let (env,x)=env in
        eval env e 
    | TInt i -> i
    | TBol b -> b

type exists_v =
| ExistsV : 't -> exists_v

let typecheck_eval e =
    let tet = typecheck CEmpty e in
    match tet with
    | Exists (te,t) -> ExistsV (eval () te)

let v1 = typecheck_eval e1
let v3 = typecheck_eval e3
let v4 = typecheck_eval e4
let v5 = typecheck_eval e5
let v6 = typecheck_eval e6
let v7 = typecheck_eval e7
let v8 = typecheck_eval e8
let v9 = typecheck_eval e9

以下是我遇到困难的部分以及我如何解决它们:
  1. 为了正确输入已键入的表达式texp,需要将环境的类型内置于texp的类型中。这意味着,正如gasche所指出的那样,我们需要某种De Bruijin符号。最简单的方法只是Var0和VarS。如果要使用变量名,我们只需预处理AST。
  2. 表达式typ的类型需要包括要匹配的变体类型以及我们在已键入的表达式中使用的类型。换句话说,这也需要是一个GADT。
  3. 我们需要三个证明才能找出类型检查器中的正确类型。这些是is_equal、is_integer和is_bool。is_equal的代码实际上在OCaml手册中,在高级示例下。具体来说,请查看eq_type的定义。
  4. 未键入的AST的类型exp实际上也需要是GADT。lambda抽象需要访问typ,它是一个GADT。
  5. 类型检查器返回一个存在类型,即已键入的表达式和类型。我们需要两者才能让程序检查类型。此外,我们需要存在性,因为未键入的表达式可能具有类型,也可能没有。
  6. 存在类型exists_texp公开了环境/上下文的类型,但没有类型。我们需要这个类型以正确地进行类型检查。
  7. 一旦设置好一切,求值器将严格遵循类型规则。
  8. 将类型检查器与求值器组合的结果必须是另一个存在类型。预先,我们不知道结果类型,因此我们必须将其隐藏在存在性包中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接