我有一个 Ring 的模块签名。 IntRing (Z) 很容易定义,但我想创建 IntRingModP (Z_p)。如何在创建模块时将 P 传递给仿函数来设置它?

module IntRing : Ring = struct
  type t = int
  let zero = 0
  let one = 1
  let add a b = a+b
  let mult a b = a*b
  let compare = compare
  let equal a b = (a=b)
  let to_string = Int.to_string
  let print a = print_string (to_string a)
end;;

module IntRingModP (P : Int) : Ring = struct
  let p = P
  type t = int
  let zero = 0 mod p
  let one = 1 mod p
  let add a b = (a+b) mod p
  let mult a b = (a*b) mod p
  let compare a b = compare (a mod p) (b mod p)
  let equal a b = ((a mod p) = (b mod p))
  let to_string a = Int.to_string (a mod p)
  let print a = print_string (to_string a)
end;;

这导致 File "polynomials.ml", line 25, characters 24-27:Error: Unbound module type Int

最佳答案

仿函数只能将模块作为参数。因此,您需要创建一个包装 int 的新模块类型:

module type IntT = sig
    val x : int
end;;

module IntRingModP (P : IntT) : Ring = struct
    let p = P.x
    type t = int
    let zero = 0 mod p
    let one = 1 mod p
    let add a b = (a+b) mod p
    let mult a b = (a*b) mod p
    let compare a b = compare (a mod p) (b mod p)
    let equal a b = ((a mod p) = (b mod p))
    let to_string a = Int.to_string (a mod p)
    let print a = print_string (to_string a)
end;;

希望有帮助。

关于ocaml - 我可以将值传递给 Ocaml 中的仿函数吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31129672/

10-11 06:50