Catamorphisms in 60 seconds
Catamorphisms. Recently I've seen this word popping up in some blog posts (often Haskell-related). Sounds fancy, and when I try to look it up, I run into stuff that is probably really deep, but looks like gobbledygook to me. (Likely because my brain doesn't really grok complex math stuff too well.)
What this word actually means is a technique where you take a number of values, process them in some way, and end up with fewer values (often a single one). A good example would be, computing the sum of a list of numbers.
In Python, one way to do this used to be using reduce (and that still works, but has been superseded by the sum built-in). Using this approach actually illustrates the concept well, known as folding in functional languages.
>>> numbers = [3, 6, 8, 12, -5] >>> reduce(lambda x, y: x+y, numbers) 24
In other words, a catamorphism is just a fold. Oh, and the opposite (an "unfold") is called an anamorphism.
That's really all there is to it. (Of course, folding can and does get much more complex, but that's a different story.)