2012-11-24 11 views
5

私は2つのモジュールを持っています。一つは、バリアント型定義:Ocamlのコンストラクタ名の略語

module A = struct 
    type foo = Bar of material | Baz | Boo 

    (* other stuff *) 
end 

およびI「はsが別のモジュールのコンストラクタのように左手側の両方

module B = struct 
    type foo = A.foo (* I can abbreviate A.foo by assigning it a local alias *) 

    let f (x : foo) = match x with 
    | Bar m  -> Bar (g m) (* Any way to abbreviate Bar and friends? *) 
    | Baz | Boo -> x 
end 

バリアントfooを使用できるようにしたいが、"referring to named objects"あたりI Uを避けるスキップする方法はあり

let f (x : foo) = match x with 
    | A.Bar m   -> A.Bar (g m) 
    | A.Baz | A.Boo -> x 

モジュールパスとバリアント名を接頭辞に持ちますopenの短いモジュールパスを歌い、他のすべてのものをAから引き出しますか?

答えて

9

あなたがローカルで開くことができます。以下のものが露出するようにあなたがサブモジュールでBarを定義することができ

let f (x : foo) = A.(match x with 
    | Bar m  -> Bar (g m) 
    | Baz | Boo -> x) 

または

let f (x : foo) = 
    let open A in 
    match x with 
    | Bar m  -> Bar (g m) 
    | Baz | Boo -> x) 

を:

module A = struct 
    module BasicDataAndOps = struct 
    type foo = Bar of material | Baz | Boo 
    end 
    open BasicDataAndOps 
    (* other stuff *) 
end 

module B = struct 
    open A.BasicDataAndOps 
    ... 

使用する場合の外パターンでは、Bで「スマートコンストラクタ」を定義できます:

let bar m = A.Bar m 

ETA:タイプ定義を再記述する可能性について忘れましたが、Ashish Argwalの答え:type foo = A.foo = Bar of material | Baz | Booに記載されています。あなたの例にすでにタイプの省略形があることを考えれば、これが最良の答えです。

type-based label disambiguationにはいくつかの作業がありますが、役立つかもしれませんが、言語に受け入れられない可能性があります。

+0

ブリリアント。ありがとう。 –

+1

「バックグラウンドで」作業する場合、[タイプベースのラベル曖昧さ除去の提案](http://gallium.inria.fr/~scherer/gagallium/resolving-field-names/)を参照している場合は、(1 )それは最終的に受け入れられないかもしれませんし、(2)レコードラベルのためだけでなく、(多形ではない)バリアントコンストラクタでもうまくいくはずです。 – gasche

+1

OCamlでは 'open in'構文がバージョン3.12から上に利用可能です。 – didierc

2

lukstafiの回答に加えて、B.fooを定義するときに、コンストラクタを再記述することもできます。

module A = struct 
    type foo = Bar | Baz 
end 

module B = struct 
    type foo = A.foo = Bar | Baz 

let f (x : foo) = match x with 
    | Bar -> "bar" 
    | Baz -> "baz" 

end 
+0

これは[3.2](http://askra.de/software/ocaml-doc/3.12/manual016.html#toc54)の* type-equation *ビットですか? –