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.)
Sam said,
January 11, 2008 @ 10:52 am
This paper is a great introduction to catamorphisms, anamorphisms, and more:
http://citeseer.ist.psu.edu/meijer91functional.html
Hans Nowak said,
January 11, 2008 @ 11:15 am
Thanks. I can actually make a bit of sense of it. :-) I was also wondering if 'filter' would be a catamorphism... according to this paper it is.
Ulisses Costa said,
January 16, 2008 @ 7:47 am
@Hans Nowak
Any recursive function f :: [a] -> X could be defined as a catamorphism.
In 'filter' 'X' type is '[a]'.