Last active
August 29, 2015 14:06
-
-
Save DrBoolean/9261ccb5a620ea22d8a2 to your computer and use it in GitHub Desktop.
Non empty list comonad in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var _One = function(v) { | |
| this.value = v; | |
| }; | |
| var _Many = function(v, vs) { | |
| this.value = v; | |
| this.tail = vs; | |
| }; | |
| var One = function(x) { return new _One(x); }; | |
| var Many = function(v, vs) { return new _Many(v, vs); } | |
| _One.prototype.map = function(f) { | |
| return One(f(this.value)); | |
| }; | |
| _One.prototype.from = function() { | |
| return this.value; | |
| }; | |
| _One.prototype.extend = function(f) { | |
| return One(f(this)); | |
| }; | |
| _Many.prototype.from = function() { | |
| return this.value; | |
| }; | |
| _Many.prototype.map = function(f) { | |
| return Many(f(this.value), this.tail.map(f)); | |
| }; | |
| _Many.prototype.extend = function(f) { | |
| return Many(f(this), this.tail.extend(f)); | |
| }; | |
| var sum = function(xs) { | |
| if(!xs.tail) return xs.value; | |
| return xs.value + sum(xs.tail); | |
| }; | |
| var x = Many(3, Many(4, One(1))); | |
| var result = x.extend(sum); | |
| console.log("X", result); | |
| // X { value: 8, tail: { value: 5, tail: { value: 1 } } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment