|
| 1 | +// Video: https://www.youtube.com/watch?v=WH5BrkzGgQY |
| 2 | + |
| 3 | +const daggy = require('daggy') |
| 4 | +const compose = (f, g) => x => f(g(x)) |
| 5 | +const id = x => x |
| 6 | + |
| 7 | + |
| 8 | +//===============Define Coyoneda========= |
| 9 | + |
| 10 | +// create constructor with props 'x' and 'f' |
| 11 | +// 'x' is our value, 'f' is a function |
| 12 | +const Coyoneda = daggy.tagged('x', 'f') |
| 13 | + |
| 14 | +// map composes the function |
| 15 | +Coyoneda.prototype.map = function(f) { |
| 16 | + return Coyoneda(this.x, compose(f, this.f)) |
| 17 | +} |
| 18 | + |
| 19 | +Coyoneda.prototype.lower = function() { |
| 20 | + return this.x.map(this.f) |
| 21 | +} |
| 22 | + |
| 23 | +// lift starts off Coyoneda with the 'id' function |
| 24 | +Coyoneda.lift = x => Coyoneda(x, id) |
| 25 | + |
| 26 | + |
| 27 | +//===============Map over a non-Functor - Set ========= |
| 28 | + |
| 29 | +// Set does not have a 'map' method |
| 30 | +const set = new Set([1, 1, 2, 3, 3, 4]) |
| 31 | + |
| 32 | +console.log("Set is: ", set) |
| 33 | + |
| 34 | +// Wrap set into Coyoneda with 'id' function |
| 35 | +const coyo_result = Coyoneda.lift(set) |
| 36 | + .map(x => x + 1) |
| 37 | + .map(x => `${x}!`) |
| 38 | + |
| 39 | +console.log("Mapped over Set is: ", coyo_result) |
| 40 | + |
| 41 | +// equivalent to buildUpFn = coyo_result.f, our_set = coyo_result.x |
| 42 | +const {f: builtUpFn, x: our_set} = coyo_result |
| 43 | + |
| 44 | +console.log("builtUpFn is: ", builtUpFn, "; our_set is: ", our_set) |
| 45 | + |
| 46 | +our_set |
| 47 | + .forEach(n => console.log(builtUpFn(n))) |
| 48 | +// 2! |
| 49 | +// 3! |
| 50 | +// 4! |
| 51 | +// 5! |
| 52 | + |
| 53 | + |
| 54 | +//===============Lift a functor in (Array) and achieve Loop fusion========= |
| 55 | +Coyoneda.lift([1,2,3]) |
| 56 | + .map(x => x * 2) |
| 57 | + .map(x => x - 1) |
| 58 | + .lower() |
| 59 | +// [ 1, 3, 5 ] |
| 60 | + |
| 61 | + |
| 62 | +//===============Make Any Type a Functor========= |
| 63 | +// Any object becomes a functor when placed in Coyoneda |
| 64 | + |
| 65 | +const Container = daggy.tagged('x') |
| 66 | + |
| 67 | +const tunacan = Container("tuna") |
| 68 | + |
| 69 | +const res = Coyoneda.lift(tunacan) |
| 70 | + .map(x => x.toUpperCase()) |
| 71 | + .map(x => x + '!') |
| 72 | + |
| 73 | + |
| 74 | +const {f: fn, x: can} = res |
| 75 | +console.log(fn(can.x)) |
| 76 | +// TUNA! |
0 commit comments