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.
:: means 2 camel humps, ' means 1 hump!
Every function in OCaml takes exactly one value and returns exactly one result. For instance, our squareRoot function takes one float value and returns one float value. The advantage of always taking one argument and returning one result is that the language is extremely uniform.
Pattern matching comes up in several places in OCaml: as a powerful control structure combining a multi-armed conditional, unification, data destructuring and variable binding; as a shortcut way of defining functions by case analysis; and as a way of handling exceptions.
This is a way to indicate there is no value for an argument. It's necessary to do this in ML because all functions are unary. You can't have a function with zero arguments, so instead you pass an argument containing no information, which is () .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With