2

我有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} )print true

所以我尝试了这个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<并替换它。而且我觉得没有吸引力。

4

1 回答 1

1

OCaml 不支持 adhoc 多态性,但是您可以将自定义运算符放在一个模块中,您可以只在需要它的地方打开该模块:

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

...

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

这样,<tree仅在 s 内部起作用,Infix.( ... )并且仍然在其外部引用Pervasives.(<)

于 2019-03-02T13:59:33.557 回答