Skip to content
This repository has been archived by the owner. It is now read-only.

Encoding ADT's robustly #121

rehno-lindeque opened this issue Mar 13, 2012 · 1 comment


None yet
2 participants
Copy link

commented Mar 13, 2012

Hi! I noticed that roy uses 'instanceof' quite pervasively, especially for pattern-matching ADT's.

Instanceof tends to have trouble when doing cross-framescripting and I suspect also in webworkers etc.

One possible solution is to leverage the internal [[CLASS]] property instead as suggested by various by people around the web:

However, there is also the problem of serializing ADT's to JSON, which I think will be pretty common when communicating with a remote server. I'd like to suggest perhaps considering an encoding that includes the constructors?
E.g. Possibly something in the style of


data NestedADT = NestedConstructor Number
data ADT = Constructor Number Number NestedADT

then this

let adt = Constructor 0 1 (NestedConstructor 2)

might be represented as

{ ADT_Constructor: [ 0, 1, { NestedADT_NestedConstructor: [ 2 ] } ] } 

or perhaps differentiating between constructors that take multiple arguments and constructors that take a single argument

{ ADT_Constructor: [ 0, 1, { NestedADT_NestedConstructor: 2 } ] } 

on the other hand, simply using arrays might be faster?

[ "ADT_Constructor", 0, 1, [ "NestedADT_NestedConstructor", 2 ] ] ] which case the code to match the nested constructors might need to do something like

Array.isArray(adt[3]) && adt[3][0] === "NestedADT_NestedConstructor" 

Which I suspect should also be pretty efficient given that Array.isArray is a native function (pure speculation though).

P.S. Perhaps it is useful to support a similar pattern matching mechanism for Lists and ADT's in order to make the generated js look uniform?


let lst = [5, 202.2, "matchthis"]
match lst
  case [x, _, "matchthis"] = console.log x "was matched"
  otherwise = console.log "no match"



This comment has been minimized.

Copy link

commented Aug 5, 2013

The [[Class]] solution has its own problem, which is that it's only doing string comparison. In contrast, instanceof checks actual references, so it's less prone to false positives.

I propose that serialization and deserialization with type information is not something Roy should try to automate at a language level. Instead, that should be left to libraries such as HydrateJS.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
You can’t perform that action at this time.