Last active
July 13, 2016 23:12
-
-
Save TrevorBasinger/217eb80e52b4928b594e to your computer and use it in GitHub Desktop.
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 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' ] } |
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
Sorry didn't catch the
of
issue at first.of
is like haskell'sreturn
. 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