I need to represent a set of elements... As there is an order relation among these elements, I decide to use a lattice (instead of a list or a map...) to represent them, where the function included
is used to check the order.
Each element has several attributes which represent their properties.
The 1) implementation is quite normal as follows:
module m = struct
type t =
| C0 | C1 | C2 ...
let get_att0 (x: t) : string =
| C0-> "C0"
| C0-> "C1"
| C0-> "C2"
let get_att1 (x: t) : int =
| C0-> 1
| C0-> 2
| C0-> 3
let get_att2 (x: t) : bool =
| C0-> true
| C0-> false
| C0-> true
let included (x0: t) (x1: t) : bool =
...
end
The 2) implementation makes use of an internal type record
:
module m = struct
type t =
| C0 | C1 | C2 ...
type record =
{ att0: string; att1: int; att2: bool ... }
let get_record (x: t) : record =
| C0 -> { att0 = "C0"; att1 = 1; att2 = true ... }
| C1 -> { att0 = "C1"; att1 = 2; att2 = false ... }
| C2 -> { att0 = "C2"; att1 = 3; att2 = true ... }
let get_att0 (x: t) : string =
(get_record x).att0
let get_att1 (x: t) : int =
(get_record x).att1
let get_att2 (x: t) : bool =
(get_record x).att2
let included (x0: t) (x1: t) : bool =
...
end
Could anyone tell me which implementation is more conventional, and more efficient in practice?
Most of the time, the implementation 1) would be used as in the second you are creating some workaround to write shorter but less clear code. Also, you are creating an intermediate struct that will be GCed just after being created so it's not very performant (don't know if ocaml will optimize this).
And if you want objects, there is that feature in OCaml: http://caml.inria.fr/pub/docs/manual-ocaml/manual005.html .