Psellos
Contemporary Development With Functional Programming

Sliding Tile Puzzle, Self-Contained OCaml Webapp

March 21, 2020

I just finished coding up another webapp in OCaml. I thought it would be cool to publish the sources of a small, completely self-contained app. It’s a sliding tile puzzle coded entirely in OCaml, using a few of the BuckleScript extensions. There are no dependencies on any frameworks or the like aside from the Js modules of BuckleScript. The app itself consists of just one JavaScript file—no images, nothing else.


You can try out the puzzle or get the sources at the Slide24 page.

I also tried to make a clean DOM interface based on experience with the Cassino and Schnapsen apps. I think it came out well, at least for these self-contained webapps.

The idea for the DOM interface is that it should expose only abstract types, but that there should be a subtype relation based on the JavaScript DOM. It turns out that you can do this pretty easily using private declarations. Types for contents of a document look like this:

type node
type text = private node
type element = private node
type canvas = private element
type box = private element
type div = private box
type span = private box
type button = private box

So, the interface reveals nothing whatsoever about the types except that they participate in a subtype relation. text and element are subtypes of node, canvas is a subtype of element, and so on. node is the supertype of all the document content types.

What this means is that you can pass a canvas or a button to a function that expects an element, and so on. I don’t find the necessity to use explicit supertype coercion to be too much trouble when working with non-parameterized types.

let style = Pseldom.(element_style (mybutton :> element)) in
. . .

It seems to me this captures pretty much everything that I want from the object-oriented approach without the usual complicated baggage. I think inheritance is more often a hindrance than a help. It’s too dependent on implementation details, and is associated with too many informal (unenforceable) descriptions of how to write subclasses of each class without messing up the semantics.

I’ve never used private declarations before, but they seem to have created exactly the structure I was hoping for.

Posted by: Jeffrey

Comments

blog comments powered by Disqus