Mar*_*ade 26 c# f# functional-programming catamorphism recursion-schemes
我正在尝试了解catamorphisms,我已经阅读了维基百科文章以及F#博客上F#主题系列中的第一篇文章.
我理解这是折叠的概括(即,将许多值的结构映射到一个值,包括值列表到另一个列表).我认为折叠列表和折叠树是一个典型的例子.
可以使用LINQ的Aggregate
运算符或其他一些更高阶的方法在C#中显示它吗?
Bri*_*ian 28
LINQ的Aggregate()仅适用于IEnumerables.Catatorphisms通常指的是任意数据类型的折叠模式.所以Aggregate()是IEnumerables FoldTree(下面)对Trees(下图)的内容; 两者都是各自数据类型的catamorphisms.
我将系列的第4部分中的一些代码翻译成了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);
}
}
Run Code Online (Sandbox Code Playgroud)
人们可以折叠树木,例如测量两棵树是否有不同的节点:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在第二个示例中,另一个树的重建方式不同:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在第三个例子中,折叠树用于绘图:
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))));
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ade 11
我一直在做更多阅读,包括关于使用catamorphisms("香蕉")进行函数式编程的Micorosft Research论文,似乎catamorphism只是指任何采用列表并通常将其分解为单个值(IEnumerable<A> => B
)的函数,像Max(),Min(),在一般情况下,Aggregate(),都是列表的catamorphisms.
我之前的印象是它提到了一种创建可以概括不同折叠的函数的方法,因此它可以折叠树和列表.实际上可能还有这样的东西,某种类型的仿函数或箭头,但现在这超出了我的理解水平.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这样我们可以在main中创建一棵树:
var Tree =
new Node(4,
new Node(2,
new Node(1),
new Node(3)
),
new Node(6,
new Node(5),
new Node(7)
)
);
Run Code Online (Sandbox Code Playgroud)
我们在Node
的命名空间中定义了通用的fold函数:
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)
);
}
Run Code Online (Sandbox Code Playgroud)
对于变形,我们应指定数据状态,节点可以为空或有子级。通用参数决定了我们在这两种情况下的操作。注意迭代策略(在这种情况下为递归)隐藏在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;
}
Run Code Online (Sandbox Code Playgroud)
我们可以写
public static int sum_tree_fold(Node tree) {
return Node.fold(
(x, l, r) => x + l + r,
0,
tree
);
}
Run Code Online (Sandbox Code Playgroud)
优雅,简单,经过类型检查,可维护等。易于使用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
);
}
Run Code Online (Sandbox Code Playgroud)
F#在“简洁”类别中获胜,In_Order_fold
但是当该语言提供了用于构造和使用列表的专用运算符时,这是可以预期的。
C#和F#之间的巨大差异似乎是由于F#使用闭包来充当隐式数据结构来触发尾部调用优化。Brian的答案中的示例还考虑了F#中的优化,以躲避重构树。我不确定C#是否支持尾部调用优化,也许In_Order_fold
可以写得更好,但是在讨论处理这些Catamorphism时C#的表现力如何时,这些要点都不重要。
在语言之间翻译代码时,您需要了解该技术的核心思想,然后根据语言的原语来实现该思想。
也许现在您可以说服您的C#同事更加认真地对待折叠。