Skip to content

Anamorphisms and Catamorphisms

Anamorphisms

Anamorphisms are functions that map from some object to a more complex structure containing the type of the object. It is the process of unfolding a simple structure into a more complex one. Consider unfolding an integer to a list of integers. The integer is our initial object and the list of integers is the more complex structure.

Sample code

function downToOne(n) {
  const list = [];

  for (let i = n; i > 0; --i) {
    list.push(i);
  }

  return list;
}

downToOne(5)
  //=> [ 5, 4, 3, 2, 1 ]

Catamorphisms

Catamorphisms are the opposite of Anamorphisms, in that they take objects of more complex structure and fold them into simpler structures. Take the following example product which take a list of integers and returns a single integer.

Sample code

function product(list) {
  let product = 1;

  for (const n of list) {
    product = product * n;
  }

  return product;
}

product(downToOne(5)) // 120

External resources