d3.jsjs-of-ocaml

Wrapping fused getter-setter functions


I'm having trouble wrapping a subset of d3-force using jooc. The library does not use object properties and instead implements fused getter-setter functions, e.g.

simulation.force("x", d3.forceX())  // setter
simulation.force("x")               // getter

I'd like to find a way to emulate the same kind of polymorphism in OCaml. Here's what I currently have

module Force = struct
  class type force = object
    (* not important *)
  end

  let x (): force Js.t = Js.Unsafe.meth_call __d3 "forceX" [||]

  class type simulation = object
    method force : string -> #force Js.t -> unit Js.meth
  end

  let simulation nodes: simulation Js.t =
    Js.Unsafe.(meth_call __d3 "forceSimulation" [|inject nodes|])
end

And here's what I'm after

let s = Force.simulation nodes in begin
  s##force "x" (Force.x ())
  s##force "x"  (* wishful thinking *)
 end

Solution

  • class type simulation = object
      method force_set : Js.js_string Js.t -> #force Js.t -> unit Js.meth
      method force : Js.js_string Js.t -> #force Js.t Js.meth
    end