11

GADT を使用して、OCaml で単純なラムダ計算のような DSL をどのように定義しますか? 具体的には、型チェッカーを適切に定義して、型指定されていない AST から型付き AST に変換する方法がわかりません。また、コンテキストと環境の正しい型もわかりません。

OCaml の従来のアプローチを使用した単純なラムダ計算のような言語のコードを次に示します。

(* 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

現在、これを GADT を使用するものに変換しようとしています。これが私のスタートです

(* 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 の正しい型を定義する方法がわかりません。通常、型には変数名を指定しますが、このコンテキストでそれを行う方法がわかりません。次に、関数の型チェックでコンテキストの正しい型がわかりません。以前はある種のリストを使用していましたが、今ではそのリストのタイプについて確信が持てます。第 3 に、コンテキストを除外した後、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 

これは完全に理にかなっています。これは、タイプチェックの正しいタイプがどうあるべきかわからないという問題です。

いずれにせよ、これらの機能をどのように修正しますか?


編集 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
4

2 に答える 2

8

用語表現で適切な型付けを強制する場合は、型環境 (および変数) の表現方法を変更する必要があります。文字列から値へのマッピングを細かく型付けすることはできません (マッピングを表す型は同種です)。古典的な解決策は、変数名の代わりにDe Bruijn インデックス(厳密に型指定された数値) を使用した変数の表現に移行することです。最初に型指定されていない世界でその変換を実行し、次に型指定されていない -> GADT パスでの入力のみを気にすることが役立つ場合があります。

以下は、厳密に型指定された変数の GADT 宣言を大まかにスケッチしたものです。

type (_, _) var =
  | Z : ('a, 'a * 'g) var
  | S : ('a, 'g) var -> ('a, 'b * 'g) var

typeの値は、 typeの環境から type('a, 'g) varの値を抽出する方法の説明として理解する必要があります。環境は、右にネストされたタプルのカスケードによって表されます。ケースは環境内の最初の変数を選択することに対応しますが、ケースは最上位の変数を無視し、環境のより深いところを調べます。'a'gZS

Shayan Najd は、このアイデアの (Haskell) 実装をgithub で公開しています。GADT 表現または型チェック/変換コードを自由に見てください。

于 2014-03-27T08:32:42.053 に答える
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. 型付けされた式のテキストを正しく入力するには、環境の型をテックスの型に組み込む必要がありました。これは、Gasche が正しく指摘したように、ある種の De Bruijin 記法が必要であることを意味します。最も簡単なのは、Var0 と VarS だけでした。変数名を使用するには、AST を前処理するだけです。
  2. 式の型 typ には、一致するバリアント型と、型付き式で使用する型の両方を含める必要がありました。つまり、これも GADT である必要がありました。
  3. 型チェッカーで正しい型を探し出すには、3 つの証明が必要です。これらは、is_equal、is_integer、および is_bool です。is_equal のコードは、実際には OCaml マニュアルのAdvanced examplesにあります。具体的には、eq_type の定義を見てください。
  4. 型指定されていない AST の型 exp も、実際には GADT である必要があります。ラムダの抽象化には、GADT である typ へのアクセスが必要です。
  5. 型チェッカーは、型付き式と型の両方の存在型を返します。プログラムに型をチェックさせるには両方が必要です。また、型指定されていない式には型がある場合とない場合があるため、存在論が必要です。
  6. 存在タイプの exists_texp は、環境/コンテキストのタイプを公開しますが、タイプは公開しません。型チェックを適切に行うには、この型を公開する必要があります。
  7. すべてがセットアップされると、エバリュエーターは型規則に正確に従います。
  8. 型チェッカーとエバリュエーターを組み合わせた結果は、別の存在型でなければなりません。アプリオリに、結果の型がわからないため、存在するパッケージで非表示にする必要があります。
于 2014-03-28T05:25:01.800 に答える