I would like to represent two types of integers in my OCaml program and have the compiler emit an error when one type is used in place of the other. My program converts between the two integer types, and a large fraction of the run time is spent operating on such values. If possible, I would like arithmetic operations to run on unboxed values. I implemented a module that defines such a type, and that implements the +, -, /, * operators. But my understanding is that the operations run on boxed values. Is there a way of getting the same behavior with unboxed values?
module SkipInts = struct
type t = Int of int | SkipInt of int
end
You could use private type abbreviations to create a distinct type for SkipInt represented as an int:
module SkipInt : sig
type t = private int
val of_int : int -> t
val to_int : t -> int
end = struct
type t = int
let of_int x = x
let to_int x = x
end
let _: SkipInt.t = SkipInt.of_int 42
let _: int = (SkipInt.of_int 42 :> int) (* :> can be used instead of SkipInt.to_int *)
let _: SkipInt.t = (42 :> SkipInt.t) (* Error: Type int is not a subtype of SkipInt.t *)
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