[英]ocaml type within a type
如果我在模塊狀態中有類型
type state = {x: int; y: int}
我在模塊游戲中有另一種類型
type game = State.state
如何在類型游戲的對象中訪問記錄值?
例如,如果我有一個游戲“g”,gx給我一個“未綁定的記錄字段標簽x”錯誤。
字段的名稱位於State
模塊名稱空間中。 你可以說g.State.x
,或者你可以打開State
模塊。
let f g = g.State.x
要么:
open State
let f g = g.x
如果您希望字段顯示在Game
模塊命名空間中,您可以重復它們:
type game = State.state = {x: int; y: int}
您還可以使用include
工具包含State
模塊。
例如,您的Game
模塊可以說:
include State
type game = state
在任何一種情況下,您都可以參考Game.x
:
let f g = g.Game.x
要么:
open Game
let f g = g.x
還有兩種表示法只能為一個表達式打開一個模塊:
let f g = Game.(g.x)
要么:
let f g = let open Game in g.x
編輯:這是一個Unix命令行會話,顯示第一個(最簡單的)解決方案:
$ cat state.ml
type state = { x: int; y : int }
$ cat game.ml
type game = State.state
$ cat test.ml
let f (g: Game.game) = g.State.x
let () = Printf.printf "%d\n" (f { State.x = 3; y = 4})
$ ocamlc -o test state.ml game.ml test.ml
$ ./test
3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.