Skip to content

Instantly share code, notes, and snippets.

@reidev275
Last active October 20, 2022 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reidev275/6089ca7242edacc50aa8c13f2d347669 to your computer and use it in GitHub Desktop.
Save reidev275/6089ca7242edacc50aa8c13f2d347669 to your computer and use it in GitHub Desktop.
export const contramap = <A, B>(f: (b: B) => A, O: Ord<A>): Ord<B> => ({
compare: (x: B, y: B) => O.compare(f(x), f(y))
});
const stringOrd: Ord<string> = ({
compare: (x: string, y: string) => x < y ? Ordering.LT : x > y ? Ordering.GT : Ordering.EQ
})
//extending stringOrd to work on Person objects
const firstName: Ord<Person> = contramap(x => x.first, stringOrd);
const lastName: Ord<Person> = contramap(x => x.last, stringOrd);
//combining Ord<Person> instances
const lastThenFirst: Ord<Person> = append(lastName, firstName);
//composing Ord<Person> instances, inverting the lastName sort
const firstThenLastDescending: Ord<Person> = append(firstName, invert(lastName))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment