OCaml 中未装箱的类型 int

er0*_*er0 3 ocaml

我想在我的 OCaml 程序中表示两种类型的整数,并让编译器在使用一种类型代替另一种类型时发出错误。我的程序在两种整数类型之间进行转换,并且运行时间的很大一部分都花在对这些值进行操作上。如果可能的话,我希望对未装箱的值运行算术运算。我实现了一个定义此类类型的模块,并实现了 +、-、/、* 运算符。但我的理解是,操作是在装箱值上运行的。有没有办法用未装箱的值获得相同的行为?

module SkipInts = struct
  type t = Int of int | SkipInt of int
end
Run Code Online (Sandbox Code Playgroud)

gle*_*nsl 5

您可以使用私有类型缩写来创建一个不同的类型,表示SkipIntint

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 *)
Run Code Online (Sandbox Code Playgroud)