Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unboxed typed int in OCaml

Tags:

ocaml

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
like image 627
er0 Avatar asked Dec 29 '25 13:12

er0


1 Answers

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 *)
like image 183
glennsl Avatar answered Jan 01 '26 13:01

glennsl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!