Last active
April 1, 2018 19:09
-
-
Save anabastos/da23db57316a5159adc2429bf74ef1b9 to your computer and use it in GitHub Desktop.
funfunfunc
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
// Container de coisas | |
// Meio de aplicar funcoes em um valor | |
// Deve retornar valores no mesmo contexto | |
const functor = { | |
map: function(f) { return functor.of(f(this.value))}, | |
of: x => Object.assign({}, functor, {value: x}) | |
} | |
const maybe = { | |
map: function(f) { return isNothing(this.value) | |
? nothing.of() | |
: just.of(f(this.value))}, | |
of: x => Object.assign({}, maybe, {value: x}), | |
mjoin: function () { return this.value }, | |
chain: function (f) { return this.map(f).mjoin() } | |
} | |
const just = { | |
map: function(f) {return just.of(f(this.value))}, | |
of: x => Object.assign({}, just, {value: x}), | |
log: function () { console.log(`Just ${this.value}`)}, | |
mjoin: function () { return this.value }, | |
chain: function (f) { return this.map(f).mjoin() } | |
} | |
const nothing = { | |
map: f => nothing.of(), | |
of: x => Object.assign({}, nothing), | |
mjoin: function () { return nothing.of() }, | |
chain: function (f) { return this.map(f).mjoin() } | |
} | |
const add = x => x + 1 | |
const map = f => context => context.map(f) | |
const mjoin = context => context.mjoin() | |
// Chain :: M a -> (a -> M b) -> M b | |
const chain = f => compose(njoin, map(f)) | |
// transform :: Number -> Just Number | |
const transform = compose(just.of, add, add) | |
const compose = (...funcs) => x => funcs.reduceRight((y ,f) => f(y), x) | |
const isNothing = x => x === null || x === undefined | |
const log = context => context.log !== undefined | |
? context.log() | |
: console.log(context) | |
// const composed = compose(log, mjoin, map(transform), maybe.of) // Maybe Number | |
const composed = compose(log, chain(transform), chain(transform) , maybe.of) // Maybe Number | |
// chain -> something inside functor pq também usa map mas diferente do funtor ele chama mjoin pra dar flat | |
// const composed = compose(log, map(transform), map(transform) , maybe.of) // Maybe Number | |
const func1 = Array.of(1, 2, 3 ,4) //or [1, 2, 3, 4] | |
console.log(func1.map(add)) | |
const func2 = functor.of(10) | |
console.log(func2) | |
console.log(func2.map(add)) | |
console.log(map(add)(map(add)(func2))) | |
const input = 41 | |
console.log(composed(input)) | |
console.log(maybe.of(41).chain(transform).chain(transform).log()) | |
// console.log(maybe.of(41).map(transform).map(transform).log()) | |
//functor are something you can map and monads are something you can flatmap :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment