Ways to make operator `<` work on custom types

158 Views Asked by At

I have type 'a edge = {from: 'a; destination: 'a; weight: int}

and I want to have Printf.printf "%b\n" ( {from= 0; destination= 8; weight= 7} < {from= 100; destination= 33; weight= -1} ) print true

so I tried this let ( < ) {weight= wa} {weight= wb} = wa < wb

but after this, the < operator only works on 'a edge, and it means that 1 < 2 will raise an error.


the reason why I want to do this is below

I write a leftist tree

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

If I cannot make < work as I expect, I must pass in a compare lambda wherever the < is used and substitute it. And I find it unattractive.

1

There are 1 best solutions below

4
On

OCaml does not support adhoc polymorphism, but you can put the custom operator in a module that you can open locally only where you need it:

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

...

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

That way, < will work on trees only inside Infix.( ... ) and still refer to Pervasives.(<) outside it.