Skip to content

Instantly share code, notes, and snippets.

@hughfdjackson
Created April 10, 2013 22:35
Show Gist options
  • Select an option

  • Save hughfdjackson/5359071 to your computer and use it in GitHub Desktop.

Select an option

Save hughfdjackson/5359071 to your computer and use it in GitHub Desktop.
var poly = require('poly')
// The Haskell Eq Typeclass
var Eq = poly({
eq: function(a, b){ return !Eq.notEq(a, b) },
notEq: function(a, b){ return !Eq.eq(a, b) }
})
// tag the prototype with a unique value
// that poly can dispatch against later
poly.tag(String.prototype)
Eq.implement(String.prototype, {
eq: function(a, b) { return a === b }
})
Eq.eq("a", "b") // false
Eq.notEq("a", "b") // true
poly.tag(Object.prototype)
Eq.implement(Object.prototype, {
eq: function(a, b){
var ks = Object.keys(a).concat(Object.keys(b))
return ks.every(function(key){
return eq(a[key], b[key])
})
}
})
Eq.eq({ "x": "foo"}, { "x": "bar" }) // false
Eq.notEq({ "x": "foo"}, { "x": "bar" }) // true
// poly tag twice is a no-op
poly.tag(Object.prototype)
Eq.eq({ "x": "foo"}, { "x": "bar" }) // false
Eq.notEq({ "x": "foo"}, { "x": "bar" }) // true
// ad-hoc typing can happen
var primitive = poly.type();
poly.tag(String.prototype, primitive)
poly.tag(Number.prototype, primitive)
poly.tag(Boolean.prototype, primitive)
Eq.implement(String.prototype, {
eq: function(a, b) { return a === b }
})
Eq.eq(1, "f") // false
Eq.eq(1, 1) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment