Skip to content

Instantly share code, notes, and snippets.

@zaetrik
Created May 4, 2020 13:41
Show Gist options
  • Save zaetrik/9d3ecdd34beba266683c3b7031c38e53 to your computer and use it in GitHub Desktop.
Save zaetrik/9d3ecdd34beba266683c3b7031c38e53 to your computer and use it in GitHub Desktop.
Monoid Type Class Example Use Case
// The use cases for Monoids & Semigroups are pretty similar
// Not every Semigroup can be a Monoid, e.g. when there is no neutral value for empty
// An example use case for both Semigroups & Monoids
// We merge two objects together we merge them by always using the right-most non-None value
// We do this by using the getLastMonoid function from fp-ts
// Mostly taken from https://dev.to/gcanti/getting-started-with-fp-ts-monoid-ja0
import { getStructMonoid } from "fp-ts/lib/Monoid";
import { Option } from "fp-ts/lib/Option";
interface Settings {
audioQuality: Option<"High" | "Medium" | "Low">;
downloadQuality: Option<"High" | "Medium" | "Low">;
downloadWithoutWifi: Option<boolean>;
username: Option<string>;
}
const monoidSettings: Monoid<Settings> = getStructMonoid({ // getStructMonoid is the same as getStructSemigroup; for more context see https://gist.github.com/Cedomic/7528477f0ee8cd8417b0bac376ffba5a
audioQuality: getLastMonoid<"High" | "Medium" | "Low">(), // getLastMonoid is like getLastSemigroup and just returns the second parameter passed into the concat method from the Monoid
downloadQuality: getLastMonoid<"High" | "Medium" | "Low">(),
downloadWithoutWifi: getLastMonoid<boolean>(),
username: getLastMonoid<string>(),
});
const standardSettings: Settings = {
audioQuality: some("Medium"),
downloadQuality: some("Medium"),
downloadWithoutWifi: some(false),
username: some(getRandomString()); // getRandomString is a dummy function that will return something like "hg29dwo26&(ash"
};
const userSettings: Settings = {
audioQuality: some("High"),
downloadQuality: none,
downloadWithoutWifi: some(true),
username: some("Bob"),
};
// userSettings overrides standardSettings
monoidSettings.concat(standardSettings, userSettings);
/*
{
audioQuality: { _tag: 'Some', value: 'High' },
downloadQuality: { _tag: 'Some', value: 'Medium' },
downloadWithoutWifi: { _tag: 'Some', value: true },
username: { _tag: 'Some', value: 'Bob' },
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment