Skip to content

Instantly share code, notes, and snippets.

@abiodun0
Last active August 13, 2021 21:11
Show Gist options
  • Save abiodun0/f0a745e8e96b59fc722c12ab18c61236 to your computer and use it in GitHub Desktop.
Save abiodun0/f0a745e8e96b59fc722c12ab18c61236 to your computer and use it in GitHub Desktop.
Contramap and functors in js. react as an example
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