OCaml compiler check for vector lengths

╄→гoц情女王★ 提交于 2019-12-05 18:56:22

You cannot define a type family in OCaml for arrays of length n where n can have arbitrary length. It is however possible to use other mechanisms to ensure that you only GpuVector.sub arrays of compatible lengths.

The easiest mechanism to implement is defining a special module for GpuVector of length 9, and you can generalise the 9 by using functors. Here is an example implementation of a module GpuVectorFixedLength:

module GpuVectorFixedLength =
struct
module type P =
sig
  val length : int
end

module type S =
sig
  type t
  val length : int
  val create : int -> t
  val sub : t -> t -> t
end

module Make(Parameter:P): S =
struct
  type t = GpuVector.t
  let length = Parameter.length
  let create x = GpuVector.create length x
  let sub = GpuVector.sub
end
end

You can use this by saying for instance

module GpuVectorHuge = GpuVectorFixedLength.Make(struct let length = 10_000_000 end)
module GpuVectorTiny = GpuVectorFixedLength.Make(struct let length = 9 end)
let x = GpuVectorHuge.create 1
let y = GpuVectorTiny.create 1

The definition of z is then rejected by the compiler:

let z = GpuVector.sub x y
                        ^
Error: This expression has type GpuVectorHuge.t
       but an expression was expected of type int array

We therefore successfully reflected in the type system the property for two arrays of having the same length. You can take advantage of module inclusion to quickly implement a complete GpuVectorFixedLength.Make functor.

The slap library implements such kind of size static checks (for linear algebra). The overall approach is described this abstract

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!