由模块式间接产生求解类型错误

问题描述 投票:1回答:1

下面的代码产生错误类型This expression has type float but an expression was expected of type ModuleA.t,即使ModuleA.tfloat是相同的,如在ModuleA定义:

module type ModuleT =
  sig
    type t
    val to_string : t -> string
  end

module ModuleA : ModuleT =
  struct
    type t = float
    let to_string x = string_of_float x
  end

let () =
  let x = 3.0 in
  Printf.printf "%s\n" (ModuleA.to_string x)

如果我不定义模块类型ModuleT,但只有ModuleA,类型错误消失。我怎样才能解决这个类型的错误,同时保持模块类型定义?

types module ocaml
1个回答
2
投票

问题是,你是隐藏在t ModuleT的定义,由于缺乏约束你的问题显而易见的解决方案是只完全定义它:

module type ModuleT =
  sig
    type t = float
    val to_string : t -> string
  end

但根据在首位定义ModuleT的原因,这种解决方案可能不合适。例如,ModuleT因为你已经定义它,你可以提供以下定义一个ModuleB

module ModuleB : ModuleT =
  struct
    type t = int
    let to_string x = string_of_int x
    let make : int -> t = fun n -> n
  end

let () =
  let x = 3 in
  Printf.printf "%s\n" (ModuleB.to_string (ModuleB.make x))

如果t ModuleT被限制为float你不能这样做,因为int显然不会float统一。

© www.soinside.com 2019 - 2024. All rights reserved.