【问题标题】:What is a catamorphism and can it be implemented in C# 3.0?什么是 catamorphism,它可以在 C# 3.0 中实现吗?
【发布时间】:2010-09-16 19:31:47
【问题描述】:

我正在尝试了解变质现象,我已经阅读了 Inside F# 博客上的the Wikipedia articlethe series of the topic for F# 中的前几篇文章。

我知道这是折叠的泛化(即,将多个值的结构映射到一个值,包括将值列表映射到另一个列表)。而且我认为 fold-list 和 fold-tree 是一个典型的例子。

这是否可以显示为在 C# 中使用 LINQ 的 Aggregate 运算符或其他一些高阶方法来完成?

【问题讨论】:

  • 如果这里的答案可以整合到维基百科的文章中,那就太棒了。
  • 小心创建循环引用。

标签: c# f# functional-programming catamorphism recursion-schemes


【解决方案1】:

我一直在做更多的阅读,包括一篇关于 functional programming with catamorphisms ("bananas") 的 Micorosft 研究论文,似乎 catamorphism 只是指任何接受列表和通常将其分解为单个值 (IEnumerable<A> => B),例如 Max()Min(),在一般情况下,Aggregate() 都是列表的变态。

我之前的印象是它引用了一种创建可以概括不同折叠的函数的方法,以便它可以折叠树列表。实际上可能还有这样的东西,可能是某种 functorarrow,但现在这超出了我的理解水平。

【讨论】:

  • 如你所说,一般情况是键入 IEnumerable → B 来表示列表变态。 Aggregate 因此不像列表变态那样通用,因为它的类型为T Aggregate<T>(this IEnumerable<T> src, Func<T, T, T> f)。然而,更通用的B Fold<A>(this IEnumerable<A>, B init, Func<A, B, B> f) 在 C#/.NET 中默认不可用。
  • @SimonShine 足够接近; )
【解决方案2】:

LINQ 的 Aggregate() 仅适用于 IEnumerables。 Catamorphisms 通常是指任意数据类型的折叠模式。所以Aggregate()IEnumerables FoldTree(下)是Trees(下);两者都是各自数据类型的变态。

我将part 4 of the series 中的一些代码翻译成C#。代码如下。请注意,等效的 F# 使用三个小于字符(用于泛型类型参数注释),而此 C# 代码使用超过 60 个。这就是为什么没有人在 C# 中编写此类代码的证据 - 类型注释太多。我提供代码以防它帮助了解 C# 但不了解 F# 的人玩这个。但是 C# 中的代码非常密集,很难理解。

给定以下二叉树的定义:

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

class Tree<T>   // use null for Leaf
{
    public T Data { get; private set; }
    public Tree<T> Left { get; private set; }
    public Tree<T> Right { get; private set; }
    public Tree(T data, Tree<T> left, Tree<T> rright)
    {
        this.Data = data;
        this.Left = left;
        this.Right = right;
    }

    public static Tree<T> Node<T>(T data, Tree<T> left, Tree<T> right)
    {
        return new Tree<T>(data, left, right);
    }
}

一个人可以折叠树木,例如测量两棵树是否有不同的节点:

class Tree
{
    public static Tree<int> Tree7 =
        Node(4, Node(2, Node(1, null, null), Node(3, null, null)),
                Node(6, Node(5, null, null), Node(7, null, null)));

    public static R XFoldTree<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> tree)
    {
        return Loop(nodeF, leafV, tree, x => x);
    }

    public static R Loop<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> t, Func<R, R> cont)
    {
        if (t == null)
            return cont(leafV(t));
        else
            return Loop(nodeF, leafV, t.Left, lacc =>
                   Loop(nodeF, leafV, t.Right, racc =>
                   cont(nodeF(t.Data, lacc, racc, t))));
    }

    public static R FoldTree<A, R>(Func<A, R, R, R> nodeF, R leafV, Tree<A> tree)
    {
        return XFoldTree((x, l, r, _) => nodeF(x, l, r), _ => leafV, tree);
    }

    public static Func<Tree<A>, Tree<A>> XNode<A>(A x, Tree<A> l, Tree<A> r)
    {
        return (Tree<A> t) => x.Equals(t.Data) && l == t.Left && r == t.Right ? t : Node(x, l, r);
    }

    // DiffTree: Tree<'a> * Tree<'a> -> Tree<'a * bool> 
    // return second tree with extra bool 
    // the bool signifies whether the Node "ReferenceEquals" the first tree 
    public static Tree<KeyValuePair<A, bool>> DiffTree<A>(Tree<A> tree, Tree<A> tree2)
    {
        return XFoldTree((A x, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> l, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> r, Tree<A> t) => (Tree<A> t2) =>
            Node(new KeyValuePair<A, bool>(t2.Data, object.ReferenceEquals(t, t2)),
                 l(t2.Left), r(t2.Right)),
            x => y => null, tree)(tree2);
    }
}

在第二个示例中,另一棵树的重建方式不同:

class Example
{
    // original version recreates entire tree, yuck 
    public static Tree<int> Change5to0(Tree<int> tree)
    {
        return Tree.FoldTree((int x, Tree<int> l, Tree<int> r) => Tree.Node(x == 5 ? 0 : x, l, r), null, tree);
    }

    // here it is with XFold - same as original, only with Xs 
    public static Tree<int> XChange5to0(Tree<int> tree)
    {
        return Tree.XFoldTree((int x, Tree<int> l, Tree<int> r, Tree<int> orig) =>
            Tree.XNode(x == 5 ? 0 : x, l, r)(orig), _ => null, tree);
    }
}

在第三个例子中,折叠一棵树用于绘图:

class MyWPFWindow : Window 
{
    void Draw(Canvas canvas, Tree<KeyValuePair<int, bool>> tree)
    {
        // assumes canvas is normalized to 1.0 x 1.0 
        Tree.FoldTree((KeyValuePair<int, bool> kvp, Func<Transform, Transform> l, Func<Transform, Transform> r) => trans =>
        {
            // current node in top half, centered left-to-right 
            var tb = new TextBox();
            tb.Width = 100.0; 
            tb.Height = 100.0;
            tb.FontSize = 70.0;
                // the tree is a "diff tree" where the bool represents 
                // "ReferenceEquals" differences, so color diffs Red 
            tb.Foreground = (kvp.Value ? Brushes.Black : Brushes.Red);
            tb.HorizontalContentAlignment = HorizontalAlignment.Center;
            tb.VerticalContentAlignment = VerticalAlignment.Center;
            tb.RenderTransform = AddT(trans, TranslateT(0.25, 0.0, ScaleT(0.005, 0.005, new TransformGroup())));
            tb.Text = kvp.Key.ToString();
            canvas.Children.Add(tb);
            // left child in bottom-left quadrant 
            l(AddT(trans, TranslateT(0.0, 0.5, ScaleT(0.5, 0.5, new TransformGroup()))));
            // right child in bottom-right quadrant 
            r(AddT(trans, TranslateT(0.5, 0.5, ScaleT(0.5, 0.5, new TransformGroup()))));
            return null;
        }, _ => null, tree)(new TransformGroup());
    }

    public MyWPFWindow(Tree<KeyValuePair<int, bool>> tree)
    {
        var canvas = new Canvas();
        canvas.Width=1.0;
        canvas.Height=1.0;
        canvas.Background = Brushes.Blue;
        canvas.LayoutTransform=new ScaleTransform(200.0, 200.0);
        Draw(canvas, tree);
        this.Content = canvas;
        this.Title = "MyWPFWindow";
        this.SizeToContent = SizeToContent.WidthAndHeight;
    }
    TransformGroup AddT(Transform t, TransformGroup tg) { tg.Children.Add(t); return tg; }
    TransformGroup ScaleT(double x, double y, TransformGroup tg) { tg.Children.Add(new ScaleTransform(x,y)); return tg; }
    TransformGroup TranslateT(double x, double y, TransformGroup tg) { tg.Children.Add(new TranslateTransform(x,y)); return tg; }

    [STAThread]
    static void Main(string[] args)
    {
        var app = new Application();
        //app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7,Example.Change5to0(Tree.Tree7))));
        app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7, Example.XChange5to0(Tree.Tree7))));
    }
}    

【讨论】:

  • 我的眼睛!但说真的,我尝试使用这样的示例,同时将它与我的同事的一些 F# 进行比较,他们的回答是我为什么要首先写这个。
  • 没错。当您只知道 C# 时,计算树的高度、转换树并在 WPF 画布上绘制树的概念——这些不同的任务——共享一个共同的核心,感觉很疯狂。 Tree 的代码只是加强了这种情况,如此难以理解。但是然后你用 F# 对它们进行编码,单个一次性实现有 DRY 的臭味(不要重复你自己),并且共性就在那里,很明显,并且语言让你捕捉到共性的本质。就像破解一样,你想知道你一直缺少哪些其他抽象。
  • 我要为这个答案添加书签,但我知道 30 年后我仍然无法理解这些代码的作用。 . .
  • @surfasb,看看Polymer's answer,尖括号少了!
【解决方案3】:

我知道这是一个 折叠的泛化(即映射 多值对一的结构 值,包括一个值列表 另一个列表)。

我不会说一个值。它将它映射到另一个结构中。

也许可以举个例子来说明一下。让我们说一个列表的总和。

foldr (\x -> \y -> x + y) 0 [1,2,3,4,5]

现在这将减少到 15 个。 但实际上,它可以被视为映射到一个纯粹的句法结构 1 + 2 + 3 + 4 + 5 + 0。 只是编程语言(在上面的例子中是haskell)知道如何将上面的句法结构减少到15。

基本上,变态将一个数据构造函数替换为另一个数据构造函数。在上述列表的情况下,

[1,2,3,4,5] = 1:2:3:4:5:[] (: 是 cons 运算符,[] 是 nil 元素) 上面的 catamorphism 替换为:用 + 和 [] 用 0。

它可以推广到任何递归数据类型。

【讨论】:

    【解决方案4】:

    Brian 在他的博客中发表了一系列精彩的文章。 Channel9 也有一个nice video。 .Aggregate() 没有 LINQ 语法糖,所以它是否具有 LINQ Aggregate 方法的定义是否重要?想法当然是一样的。 折叠树...首先我们需要一个节点...也许可以使用元组,但这更清楚:

    public class Node<TData, TLeft, TRight>
    {
        public TLeft Left { get; private set; }
        public TRight Right { get; private set; }
        public TData Data { get; private set; }
        public Node(TData x, TLeft l, TRight r){ Data = x; Left = l; Right = r; }
    }
    

    然后,在 C# 中我们可以创建一个递归类型,即使这很不寻常:

    public class Tree<T> : Node</* data: */ T, /* left: */ Tree<T>, /* right: */ Tree<T>>
    {
        // Normal node:
        public Tree(T data, Tree<T> left, Tree<T> right): base(data, left, right){}
        // No children:
        public Tree(T data) : base(data, null, null) { }
    }
    

    现在,我将引用 Brian 的一些代码,稍作 LINQ 风格的修改:

    1. 在 C# 中折叠称为聚合
    2. LINQ 方法是使用“this”关键字将项目作为第一个参数的扩展方法。
    3. 循环可以是私有的

    ...

    public static class TreeExtensions
    {
        private static R Loop<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> t, Func<R, R> cont)
        {
            if (t == null) return cont(leafV(t));
            return Loop(nodeF, leafV, t.Left, lacc =>
                    Loop(nodeF, leafV, t.Right, racc =>
                    cont(nodeF(t.Data, lacc, racc, t))));
        }    
        public static R XAggregateTree<A, R>(this Tree<A> tree, Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV)
        {
            return Loop(nodeF, leafV, tree, x => x);
        }
    
        public static R Aggregate<A, R>(this Tree<A> tree, Func<A, R, R, R> nodeF, R leafV)
        {
            return tree.XAggregateTree((x, l, r, _) => nodeF(x, l, r), _ => leafV);
        }
    }
    

    现在,用法很C#风格:

    [TestMethod] // or Console Application:
    static void Main(string[] args)
    {
        // This is our tree:
        //     4 
        //  2     6 
        // 1 3   5 7 
        var tree7 = new Tree<int>(4, new Tree<int>(2, new Tree<int>(1), new Tree<int>(3)),
                                new Tree<int>(6, new Tree<int>(5), new Tree<int>(7)));
    
        var sumTree = tree7.Aggregate((x, l, r) => x + l + r, 0);
        Console.WriteLine(sumTree); // 28
        Console.ReadLine();
    
        var inOrder = tree7.Aggregate((x, l, r) =>
            {
                var tmp = new List<int>(l) {x};
                tmp.AddRange(r);
                return tmp;
            }, new List<int>());
        inOrder.ForEach(Console.WriteLine); // 1 2 3 4 5 6 7
        Console.ReadLine();
    
        var heightTree = tree7.Aggregate((_, l, r) => 1 + (l>r?l:r), 0);
        Console.WriteLine(heightTree); // 3
        Console.ReadLine();
    }
    

    我还是更喜欢 F#。

    【讨论】:

      【解决方案5】:

      Brian 在第一段中的回答是正确的。但他的代码示例并没有真正反映如何以 C# 风格解决类似问题。考虑一个简单的类node

      class Node {
        public Node Left;
        public Node Right;
        public int value;
        public Node(int v = 0, Node left = null, Node right = null) {
          value = v;
          Left = left;
          Right = right;
        }
      }
      

      这样我们可以在 main 中创建一个树:

      var Tree = 
          new Node(4,
            new Node(2, 
              new Node(1),
              new Node(3)
            ),
            new Node(6,
              new Node(5),
              new Node(7)
            )
          );
      

      我们在Node的命名空间中定义了一个通用的折叠函数:

      public static R fold<R>(
        Func<int, R, R, R> combine,
        R leaf_value,
        Node tree) {
      
        if (tree == null) return leaf_value;
      
        return 
          combine(
            tree.value, 
            fold(combine, leaf_value, tree.Left),
            fold(combine, leaf_value, tree.Right)
          );
      }
      

      对于catamorphisms,我们应该指定数据的状态,节点可以是空的,或者有孩子。通用参数决定了我们在这两种情况下做什么。请注意,迭代策略(在本例中为递归)隐藏在 fold 函数中。

      现在不用写了:

      public static int Sum_Tree(Node tree){
        if (tree == null) return 0;
        var accumulated = tree.value;
        accumulated += Sum_Tree(tree.Left);
        accumulated += Sum_Tree(tree.Right);
        return accumulated; 
      }
      

      我们可以写

      public static int sum_tree_fold(Node tree) {
        return Node.fold(
          (x, l, r) => x + l + r,
          0,
          tree
        );
      }
      

      优雅、简单、类型检查、可维护等。易于使用Console.WriteLine(Node.Sum_Tree(Tree));

      添加新功能很容易:

      public static List<int> In_Order_fold(Node tree) {
        return Node.fold(
          (x, l, r) => {
            var tree_list = new List<int>();
            tree_list.Add(x);
            tree_list.InsertRange(0, l);
            tree_list.AddRange(r);
            return tree_list;
          },
          new List<int>(),
          tree
        );
      }
      public static int Height_fold(Node tree) {
        return Node.fold(
          (x, l, r) => 1 + Math.Max(l, r),
          0,
          tree
        );
      }
      

      F# 在 In_Order_fold 的简洁性类别中获胜,但当该语言提供用于构造和使用列表的专用运算符时,这是意料之中的。

      C# 和 F# 之间的巨大差异似乎是由于 F# 使用闭包作为隐式数据结构来触发尾调用优化。 Brian 的答案中的示例还考虑了 F# 中的优化,以避开重建树。我不确定 C# 是否支持尾调用优化,也许 In_Order_fold 可以写得更好,但是在讨论 C# 在处理这些变形时的表现力时,这些点都不相关。

      在语言之间翻译代码时,你需要了解该技术的核心思想,然后根据语言的原语来实现该思想。

      也许现在您可以说服您的 C# 同事更认真地对待折叠。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-10
        • 2020-09-13
        • 1970-01-01
        • 1970-01-01
        • 2012-02-25
        • 2012-09-04
        • 2011-02-27
        相关资源
        最近更新 更多