Skip to content

Instantly share code, notes, and snippets.

@Willmo36
Created March 10, 2020 21:17
Show Gist options
  • Save Willmo36/67b1da02ca0c75bda4fd98f740322cb2 to your computer and use it in GitHub Desktop.
Save Willmo36/67b1da02ca0c75bda4fd98f740322cb2 to your computer and use it in GitHub Desktop.
fp-ts FoldMap example
import * as A from "fp-ts/lib/Array";
import * as M from "fp-ts/lib/Map";
import { eqNumber } from "fp-ts/lib/Eq";
//My domain type
type User = {
name: string;
age: number;
};
//Get the monoid for Map<number, User[]>
//Notice how I don't have to define anything to do with combining Maps
//or how to combine User[]s
const monoidMapAgeUser = M.getMonoid(eqNumber, A.getMonoid<User>());
const foldMap = A.array.foldMap(monoidMapAgeUser);
//Now all we have to do is turn a single User into a 1 element Map<number, User>
//and the monoid will take care of combining the Map and Array parts
const groupByAge: (users: User[]) => Map<number, User[]> = users =>
foldMap(users, user => M.singleton(user.age, [user]));
console.log(groupByAge([]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment