我正在尝试编写一个不需要处理所有已知类型的事件的事件处理程序,并尝试使用 OCaml 多态变体类型(event.mli
)对此进行建模:
type 'events event =
[< `click of int * int | `keypress of char | `quit of int ] as 'events
(* Main loop should take an event handler callback that handles 'less than' all known event types *)
val mainLoop : ('events event -> unit) -> unit
val handler : 'events event -> unit
一个示例实现(event.ml
):
type 'events event =
[< `click of int * int | `keypress of char | `quit of int ] as 'events
let mainLoop handler =
for n = 1 to 10 do
handler begin
if n mod 2 = 0 then `click (n, n + 1)
else if n mod 3 = 0 then `keypress 'x'
else `quit 0
end
done
let handler = function
| `click (x, y) -> Printf.printf "Click x: %d, y: %d\n" x y
| `quit code -> exit code
不幸的是,这失败并出现以下错误:
File "event.ml", line 1:
Error: The implementation event.ml
does not match the interface event.cmi:
Values do not match:
val mainLoop :
([> `click of int * int | `keypress of char | `quit of int ] -> 'a) ->
unit
is not included in
val mainLoop :
([< `click of int * int | `keypress of char | `quit of int ] event ->
unit) ->
unit
File "event.ml", line 4, characters 4-12: Actual declaration
我怎样才能将实现mainLoop
推断为 type ([< `click of int * int | `keypress of char | `quit of int ] -> unit) -> unit
,即 as ('events event -> unit) -> unit
?