ocaml type within a type
Asked Answered
C

1

5

If I have a type in a module State

type state = {x: int; y: int}

and I have another type in module Game

type game = State.state

how can I access the record values in a object with type game?

For example if I have a game "g", g.x gives me an "Unbound record field label x" error.

Catalpa answered 26/11, 2012 at 2:3 Comment(0)
G
9

The names of the fields are in the State module namespace. You can say g.State.x, or you can open the State module.

let f g = g.State.x

Or:

open State

let f g = g.x

If you want the fields to appear in the Game module namespace, you can repeat them:

type game = State.state = {x: int; y: int}

You can also use the include facility to include the State module.

For example, your Game module could say:

include State
type game = state

In either of these cases, you can refer to Game.x:

let f g = g.Game.x

Or:

open Game
let f g = g.x

There are also two notations for opening a module for just a single expression:

let f g = Game.(g.x)

Or:

let f g = let open Game in g.x

Edit: Here's a Unix command-line session that shows the first (simplest) solution:

$ 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
Greeneyed answered 26/11, 2012 at 2:46 Comment(6)
hmm none of those seem to work...if I try g.State.x it says "Unbound record field label State.x" and inserting open State does not change anythingCatalpa
I tested them all, so they work for me. I assumed each module was a file: state.ml, game.ml, and test.ml. Need to compile state.ml, then game.ml, then test.ml.Greeneyed
I have mli files for game and state, would that affect their interaction in any way?Catalpa
The mli files need to define the symbols you want to use, that's really the essence. If some symbols aren't in there, then they won't be defined. For my simple example, the mli files will be identical to the ml files! But for real code, they'll be different of course.Greeneyed
@Mike: the mli files define the visibility of your types and valuesHardesty
The last 2 notations are available only starting from ver. 3.12 of OCaml.Hardesty

© 2022 - 2024 — McMap. All rights reserved.