Roy - Structural Typing
This week I implemented very simple structural typing in Roy and created a website for the project.
Structural typing is a really awesome type system feature. Here’s an example:
let obj = {x: 1, y: 2, t: "test"}
let getX a = a.x + 2
console.log (getX obj)
console.log (obj.x + obj.y)
let plusXY a = a.x + a.y
console.log (plusXY obj)
console.log (plusXY {x: 2, y: 1})
let makeXY x y = {x: x, y: y}
console.log (plusXY (makeXY 1 2))
console.log (makeXY 1 2)
// Won't compile
// plusXY {x: 1, z: 2}
console.log ((fn obj = obj.a.a + obj.a.b) {a: {a: 1, b: 2}})
let makeFun a = {f: fn b = a.x + b.y}
console.log ((makeFun {x: 1}).f {y: 2})
The idea is that an object is a subtype if it can satisfy all of another object’s properties.
Visit Roy’s website to give the language a try from your browser. I’ve only tested it in Chrome and Safari. It definitely won’t work in IE.
Please enable JavaScript to view the comments powered by Disqus.