Skip to content

Instantly share code, notes, and snippets.

@MarkusPfundstein
Last active May 25, 2018 10:38
Show Gist options
  • Save MarkusPfundstein/c66acecb7b3df2a16022048709433ec9 to your computer and use it in GitHub Desktop.
Save MarkusPfundstein/c66acecb7b3df2a16022048709433ec9 to your computer and use it in GitHub Desktop.
Product Comonad example
const Prod = t => ({
extract : () => t[1],
extend : f => Prod([t[0], f([t[0], t[1]])]),
map : f => Prod([t[0], f(t[1])]),
duplicate : () => Prod([t[0], Prod(t)])
});
Prod.of = function(t) {
return Prod(t);
};
const Student = {
id: 5,
name: "markus",
surname: "pfundstein",
domain: "hotbox.com"
}
const result =
Prod.of([Student, Student])
.map(({name, surname, domain}) => `${name}.${surname}@${domain}`)
.extend(([student, mail]) => `${student.id}, ${mail}`)
.extract();
console.log(result);
@ivenmarquardt
Copy link

This is a good example to get a first intuition what a comonad is. However, there is a little mistake in your monadic of definition. of is intended to put a value in a minimal context. For a 2-tuple the only sane definition is of = x => [x, x], which simplifies Prod.of([Student, Student]) into Prod.of(Student).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment