How to model a DOM attributes hierarchy?

Hello,

I try to build types/modules to express the nodes classes of docutils. As it follows a DOM philosophy, they form a hierarchy of classes which share common attributes.

What is an acceptable way to model this in OCaml ? Polymorphic variants or modules with a lot of includes ?

A simple, effective way is to use different types for each kind of node and express “subclassing” with explicit casting functions. It is low-tech but effective and easy to reason about. For a good example of this appraoch, see GitHub - dbuenzli/brr: Browser programming toolkit for OCaml, which uses it to model… the DOM.

Cheers,
Nicolas

Could you point to the specific file? The repo is quite large.

You can look at brr/src/brr.mli at master · dbuenzli/brr · GitHub, in particular, the as_* functions for example (which are all the identity function behind the scenes); also brr/src/jv.mli at master · dbuenzli/brr · GitHub, the low-level “casting” functions that allow transmuting any value to- and from- a plain JS value.

Cheers,
Nicolas

To expand on @nojb’s answers the cookbook explains the general pattern to model classes.

For a DOM example, you can have a look at the generic interface for DOM elements and for example specific support for the canvas element and its explicit coercion functions.

As written in the Brr FFI foreword:

In Brr we simply hide JavaScript objects behind abstract OCaml types which are acted upon using regular OCaml functions. JavaScript being quite sane about its object-orientation, the occasional mixin or inheritance relationship can be handled with explicit coercions functions.

2 Likes

It seems a simple approach to have converters instead of toying around with modules which requires usage of functors or first class modules to make inheritance appear forcibly. Not conceptually advanced but good for a first version. If I really need modules, I’ll retrofit it to that.

Thank you for your help