Skip to content

Instantly share code, notes, and snippets.

@DrBoolean
Created February 26, 2016 15:40
Show Gist options
  • Save DrBoolean/4f74b0f096f6d8e790b4 to your computer and use it in GitHub Desktop.
Save DrBoolean/4f74b0f096f6d8e790b4 to your computer and use it in GitHub Desktop.
Coyoneda Uses in JS
const daggy = require('daggy')
const compose = (f, g) => x => f(g(x))
const id = x => x
//===============Define Coyoneda=========
const Coyoneda = daggy.tagged('x', 'f')
Coyoneda.prototype.map = function(f) {
return Coyoneda(this.x, compose(f, this.f))
}
Coyoneda.prototype.lower = function() {
return this.x.map(this.f)
}
Coyoneda.lift = x => Coyoneda(x, id)
//===============Map over a non-Functor - Set =========
const set = new Set([1, 1, 2, 3, 3, 4])
const coyo_result = Coyoneda.lift(set)
.map(x => x + 1)
.map(x => `${x}!`)
const {f:f, x:our_set} = coyo_result
our_set.forEach(n => console.log(f(n)))
// 2!
// 3!
// 4!
// 5!
//===============Lift a functor in (Array) and achieve Loop fusion=========
Coyoneda.lift([1,2,3])
.map(x => x * 2)
.map(x => x - 1)
.lower()
// [ 1, 3, 5 ]
//===============Make Any Type a Functor=========
const Container = daggy.tagged('x')
const tunacan = Container("tuna")
const res = Coyoneda.lift(tunacan)
.map(x => x.toUpperCase())
.map(x => x + '!')
const {f: fn, x: can} = res
console.log(fn(can.x))
// TUNA!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment