1

私はこのようなコードを持っています:

  type boolean = T | F
  type  bexp = Const of boolean 
  |  Var of variable
  |  Bop of bop * bexp * bexp
  |  Not of bexp
  and bop = And | Or | Xor 
  and variable = { name: string; mutable value: boolean }

後で変数を作成したい場合は、次のことを行う必要があります。

let full         = Var({name ="full"; value  = F});;   

'full'を2回繰り返す必要はなく、名前を文字列として取得するための内省的な方法を考え出したいと思います。camlp4がこれに役立つと思いますが、どこから始めればよいのかわかりません。

したがって、最終的には、次のようなことができるようになりたいと思います。

let full          = Var({name = :letname:; value = F});;

ここで、:letname:は、現在のletバインディングを(この場合は「full」)の代わりに文字列として入力します。(構文:letname:は単なる提案であり、OCamlの構文と衝突しない構文の他のアイデアですか?)

このようなより簡潔な構文がおそらく望ましいでしょう:

var full = F 

その後、次のように拡張されます。

let full = Var({name = "full"; value = F});;

これはcamlp4で行うことができますか?もしそうなら、どうすればよいですか?

(さらに検討すると、:letname:構文などは、より汎用的で、より多くの領域で役立ちます)

4

2 に答える 2

3

次のことを試してください。test.mlなどの別のファイル

(* A simple syntax extension for getting the name of an identifier. *) 
open Camlp4 

(* Create an ID for the macro*) 
module Id : Sig.Id = struct 
    let name = "let'"
    let version = "1.0" 
end 

module Make (Syntax : Sig.Camlp4Syntax) = struct 
    open Sig 
    include Syntax 

    (* Extend the syntax with a let' x=e1 in e2 construction*) 
    EXTEND Gram 
    expr: [ 
        [ "let'"; x = patt ; "=" ; e1=expr; "in"; e2=expr -> 
            let name=begin match x with
                | Ast.PaId (_,Ast.IdLid(_,name)) -> name
                | _ -> failwith "Require an identifier in a let' statement."
            end in
            <:expr<
                let $x$ = $e1$ in ($str:name$,$e2$)
            >>
        ] 
    ]; 
    END 
end 

module M = Register.OCamlSyntaxExtension(Id)(Make) 

次に、でコンパイルします

 ocamlc -c -I +camlp4 dynlink.cma camlp4lib.cma -pp camlp4of.opt test.ml

トップレベル

 ocaml dynlink.cma -I +camlp4 camlp4of.cma

それで

# #load "test03.cmo";;
# let' x=1 in x;;
- : string * int = ("x", 1)

拡張子を付けてコンパイルするには、test2.mlなどの別のファイルを作成します

let' x=1 in x

次に、でコンパイルします

ocamlc -pp "camlp4of test.cmo" test2.ml
于 2012-02-11T18:56:29.903 に答える
0

はい、これは可能です。camlp4チュートリアルを読んで、それがどのように機能するかを理解し、より具体的な質問をすることから始めます。

于 2012-01-05T08:12:36.567 に答える