Last active
August 13, 2021 21:11
-
-
Save abiodun0/f0a745e8e96b59fc722c12ab18c61236 to your computer and use it in GitHub Desktop.
Contramap and functors in js. react as an example
This file contains 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
import React from 'react' | |
// Comp:: a -> JSX; | |
const Comp = g => ({ | |
fold: g, | |
contramap: f => Comp(x => g(f(x))), | |
concat: other => Comp((x) => <div> {g(x)} {other.fold(x)} </div>) | |
}); | |
// Reducer :: (a, b) -> a | |
const Reducer = g => ({ | |
fold: g, | |
contramap: f => Reducer((acc, x) => g(acc, f(x))), | |
map: f => Reducer((acc, x) => f(g(acc, x))), | |
concat: other => Reducer((acc, x) => other.fold(g(acc, x), x)) | |
}); | |
// HOC :: Component -> Component | |
const HOC = g => ({ | |
fold: g, | |
concat: other => HOC(x => g(other.fold(x))) | |
}) | |
const r = Reducer((acc, x) => acc.concat(x)).contramap(x => `this number is ${x}`).map(x => x + ' ! '); | |
console.log([1,5,6,7,8].reduce(r.fold, ' ')); | |
const TestInput = str => <h1> My name is {str}</h1> | |
const AnotherTestInput = head => <p> We are {head} </p> | |
const ResultComp = Comp(TestInput).contramap(x => x.name) | |
const ResultTwo = Comp(AnotherTestInput).contramap(x => x.job) | |
const FinalResult = ResultComp.concat(ResultTwo).fold({name: 'Abiodun', job: 'developer'}) | |
export default FinalResult; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment