使运算符`<`对自定义类型起作用的方法

时间:2019-03-02 13:20:07

标签: operator-overloading ocaml adhoc-polymorphism

我有type 'a edge = {from: 'a; destination: 'a; weight: int}

我想让Printf.printf "%b\n" ( {from= 0; destination= 8; weight= 7} < {from= 100; destination= 33; weight= -1} )打印为真

所以我尝试了let ( < ) {weight= wa} {weight= wb} = wa < wb

但是此后,<运算符仅在'a edge上起作用,这意味着1 < 2将引发错误。


我要这样做的原因如下

我写了一个左派树

type 'a leftist = Leaf | Node of 'a leftist * 'a * 'a leftist * int

let rank t = match t with Leaf -> 0 | Node (_, _, _, r) -> r

let is_empty t = rank t = 0

let rec merge t1 t2 =
  match (t1, t2) with
  | Leaf, _ -> t2
  | _, Leaf -> t1
  | Node (t1l, v1, t1r, r1), Node (t2l, v2, t2r, r2) ->
    if v1 > v2 then merge t2 t1
    else
      let next = merge t1r t2 in
      let rt1l = rank t1l and rn = rank next in
      if rt1l < rn then Node (next, v1, t1l, rn + 1)
      else Node (t1l, v1, next, rt1l + 1)

let insert v t = merge t (Node (Leaf, v, Leaf, 1))

let peek t = match t with Leaf -> None | Node (_, v, _, _) -> Some v

let pop t = match t with Leaf -> Leaf | Node (l, _, r, _) -> merge l r

如果我无法使<正常工作,则无论使用<的位置如何,我都必须传递一个比较lambda并将其替换。而且我觉得它没有吸引力。

1 个答案:

答案 0 :(得分:1)

OCaml不支持即席多态性,但是您可以将自定义运算符放在一个模块中,该模块只能在需要时在本地打开:

module Infix =
struct
  let ( > ) = ...
end

...

if Infix.(rt1l < rn) then ...

这样,<将仅在tree内部的Infix.( ... )上工作,而仍然引用其外部的Pervasives.(<)