Skip to content

Instantly share code, notes, and snippets.

@rolandpeelen
Last active February 4, 2020 11:03
Show Gist options
  • Select an option

  • Save rolandpeelen/edece975daa57c119cfaadeeffc4e96b to your computer and use it in GitHub Desktop.

Select an option

Save rolandpeelen/edece975daa57c119cfaadeeffc4e96b to your computer and use it in GitHub Desktop.
/*
* Our 'constructor' (i.e. our functor) is just a container
* of some value a and some value b, with a `get` that wraps
* them in a fixed length array so we can deconstruct it.
*/
// magicalType a b
const magicalConstructor = (a, b) => {
const aVal = a;
const bVal = b;
get = () => [aVal, bVal];
return { get };
};
/*
* Our bimap takes an f (a -> c) and a g (b -> d),
* then takes a value built with our magicalConstructor.
* We use the `get` on that to take out our a and b values,
* Subsequently, we create a new magicalValue, with f applied
* to a (making it c) and g applied to b (making it d).
*/
// bimap :: (a -> c) -> (b -> d) -> magicalType a b -> magicalType c d
const bimap = f => g => magicalValue => {
const [a, b] = magicalValue.get();
return magicalConstructor(f(a), g(b));
};
/*
* First is simply the first bit of the dimap
*/
// first :: (a -> c) -> magicalType a b -> magicalType c b
const first = f => magicalValue => {
const [a, b] = magicalValue.get();
return magicalConstructor(f(a), b);
};
/*
* Second is simply the second bit of the dimap
*/
// first :: (b -> d) -> magicalType a b -> magicalType b d
const second = g => magicalValue => {
const [a, b] = magicalValue.get();
return magicalConstructor(a, g(b));
};
/*
* We define a curried function that adds some value to some value
* We partially apply that to create a function that adds twelve
* and five.
*/
const add = a => b => a + b;
const addTwelve = add(12);
const addFive = add(5);
/*
* The syntax is a bit weird because everything is curried.
*/
const magicalValue = magicalConstructor(5, 5);
console.log(bimap(addTwelve)(addFive)(magicalValue).get()); // [17, 10]
console.log(first(addTwelve)(magicalValue).get()); // [17, 5]
console.log(second(addFive)(magicalValue).get()); // [12, 10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment