I’m trying to learn about catamorphisms and I’ve read the Wikipedia article and the first couple posts in the series of the topic for F# on the Inside F# blog.
I understand that it’s a generalization of folds (i.e., mapping a structure of many values to one value, including a list of values to another list). And I gather that the fold-list and fold-tree is a canonical example.
Can this be shown to be done in C#, using LINQ’s Aggregate operator or some other higher-order method?
LINQ’s
Aggregate()is just forIEnumerables. Catamorphisms in general refer to the pattern of folding for an arbitrary data type. SoAggregate()is toIEnumerableswhatFoldTree(below) is toTrees(below); both are catamorphisms for their respective data types.I translated some of the code in part 4 of the series into C#. The code is below. Note that the equivalent F# used three less-than characters (for generic type parameter annotations), whereas this C# code uses more than 60. This is evidence why no one writes such code in C# – there are too many type annotations. I present the code in case it helps people who know C# but not F# play with this. But the code is so dense in C#, it’s very hard to make sense of.
Given the following definition for a binary tree:
One can fold trees and e.g. measure if two trees have different nodes:
In this second example, another tree is reconstructed differently:
And in this third example, folding a tree is used for drawing: