Skip to content

Instantly share code, notes, and snippets.

@zaetrik
Created May 3, 2020 08:34
Show Gist options
  • Save zaetrik/fce575e86026fd9b7e40be04a82b71d5 to your computer and use it in GitHub Desktop.
Save zaetrik/fce575e86026fd9b7e40be04a82b71d5 to your computer and use it in GitHub Desktop.
Semigroup Type Class fold
// Semigroup's concat works only with two values
// If we would like to merge/concat more elements we have to use a function called fold
// If you understand JS's array.reduce you will understand fold
// The fold function for Semigroups from fp-ts is defined like this =>
export function fold<A>(S: Semigroup<A>): (a: A, as: ReadonlyArray<A>) => A {
return (a, as) => as.reduce(S.concat, a)
}
// It takes in a Semigroup and returns a function that takes in an initial value A and an array of A (Array<A>) and returns an A
// So it folds/reduces an Array<A> into a single value A
// Under the hood fold also uses reduce (the reducer is the concat method from the passed in Semigroup instance)
// For our previously defined semigroupProduct it would look like this =>
const product = fold(semigroupProduct) // concat is (x, y) => x * y
product(1, [1, 2, 3, 4]) // 24 => 1 * 1 * 2 * 3 * 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment