[英]ocaml how to test module with concrete types
給定以下界面:
module type Comparable = sig
type t
val compare : t -> t -> int
end
並執行:
open Comparable
module Point : Comparable = struct
type t = {x: float; y: float}
let compare p1 p2 =
match (p1, p2) with
| {x = x1; _}, {x = x2; _} -> int_of_float (x1 -. x2)
end
我將如何測試Point
? 或推薦的這樣做方式是什么?
我試過了:
let () =
(Printf.printf "%d\n" (Point.compare {x = 1.2; y = 3.4} {x = 3.5; y = 2.1}));
()
但是在我的IDE中出現了這個錯誤:
Error: Unbound record field x
如何做到這一點,以便我可以使用模塊內定義的類型,而不必訴諸於在模塊外公開該類型?
我在考慮某種create_from
方法,該方法采用對象類型並返回正確的類型。
謝謝
這里的主要問題是,您使用Comparable
簽名無意中降低了模塊的類型精度。
該簽名優先於type t = {x: float; y: float}
type t = {x: float; y: float}
僅type t
,這就是為什么
Error: Unbound record field x
一種解決方案是簡單地忽略簽名,讓OCaml自己找出簽名
module Point = struct
type t = {x: float; y: float}
let compare p1 p2 =
match (p1, p2) with
| {x = x1; _}, {x = x2; _} -> int_of_float (x1 -. x2)
end
那你可以做
Point.compare {x = 1.2; y = 3.4} {x = 3.5; y = 2.1}
沒有任何錯誤,但是您會得到警告,說記錄類型字段在當前作用域中不可見-您可以通過指定記錄的類型來解決此問題:
Point.compare {Point. x = 1.2; y = 3.4} {Point. x = 3.5; y = 2.1}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.