Skip to content

Instantly share code, notes, and snippets.

@TrevorBasinger
Last active July 13, 2016 23:12
Show Gist options
  • Select an option

  • Save TrevorBasinger/217eb80e52b4928b594e to your computer and use it in GitHub Desktop.

Select an option

Save TrevorBasinger/217eb80e52b4928b594e to your computer and use it in GitHub Desktop.
var Tuple2 = require('fantasy-tuples').Tuple2,
daggy = require('daggy'),
Writer = daggy.tagged('run');
Writer.of = function(x, y) {
return Writer(function() {
return Tuple2(x, y.concat(y.empty()));
});
};
Writer.prototype.chain = function(f) {
var writer = this;
return Writer(function() {
var result = writer.run();
var t = f(result._1).run();
return Tuple2(t._1, result._2.concat(t._2));
});
};
Writer.prototype.tell = function(y) {
var writer = this;
return Writer(function(a) {
var result = writer.run();
return Tuple2(result._1, result._2.concat(y));
});
}
Writer.prototype.map = function(f) {
return this.chain(function(a) {
return Writer.of(f(a));
});
};
Writer.prototype.ap = function(a) {
return this.chain(function(f) {
return a.map(f);
});
};
//////////////////////////////////////////////////
// Unofficial Semi-Tests
//////////////////////////////////////////////////
require('pointfree-fantasy').expose(global);
var add = curry (function(x, y) {
return Writer.of(x + y, ["Adding " + y + " to " + x + "."]);
});
w = Writer.of(1, ["this is a test"])
.chain(add(3))
.chain(add(5))
.chain(add(8))
.tell(["End Test"])
console.log(w.run());
// Output:
// { _1: 17,
// _2:
// [ 'this is a test',
// 'Adding 1 to 3.',
// 'Adding 4 to 5.',
// 'Adding 9 to 8.'
// 'End Test' ] }
@DrBoolean

Copy link
Copy Markdown

Sorry didn't catch the of issue at first. of is like haskell's return. So here, it should be separate from the constructor. It's probably best to do: new Writer(1, ["this is a test"]). Otherwise, it's looking awesome

@TrevorBasinger

Copy link
Copy Markdown
Author

Ah! Okay cool. Thanks for your help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment