Search code examples
syntaxocamlinfix-notationinfix-operator

Infix operators with 3 parameters ocaml


Is it possible in ocaml to define an operator like the array set function which can be written a.(n)<-v?

The OCaml manual explains how to define 2-parameters infix operators but not 3-parameters operators. I would like to know if there is a way to define a function , a bit like the Array.set method which can be called using the a.(n)<-v syntax.

I would like to create a new operator that could be called using this syntax: a[b<-c]

I tried some things like this:

let ([<-]) a b c = ... 
let (#1[#2<-#3]) a b c =...

but these didn't work.

Thanks in advance for your help!


Solution

  • It is possible to define custom indexing operators (https://ocaml.org/manual/indexops.html):

    let (.?[]) h k = Hashtbl.find_opt h k
    let (.![]<-) h k x = Hashtbl.replace h k x
    let test =
      let h = Hashtbl.create 5 in
       h.![1] <- "one";
      assert (h.?[1] = Some "one")
    

    but not generic mixfix operator.

    In your case, it might possible to decompose your operator in two:

    type ('a,'b) s = Subst of 'a * 'b
    let (.%[]) a (Subst(a,b)) = ...
    let (<--) a b = Subst(a,b)
    

    which is sufficient to write

    let f a x y= a.%[x <-- y]