欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中面向对象编程中的函数式编程详解

程序员文章站 2022-04-15 08:58:18
介绍 使用函数式编程来丰富面向对象编程的想法是陈旧的。将函数编程功能添加到面向对象的语言中会带来面向对象编程设计的好处。 一些旧的和不太老的语言,具有函数式编程和面向对象的编程: 例如,Smalltalk和Common Lisp。 最近是Python或Ruby。 面向对象编程中仿真的函数式编程技术 ......

介绍

使用函数式编程来丰富面向对象编程的想法是陈旧的。将函数编程功能添加到面向对象的语言中会带来面向对象编程设计的好处。

一些旧的和不太老的语言,具有函数式编程和面向对象的编程:

  • 例如,smalltalk和common lisp。
  • 最近是python或ruby。

面向对象编程中仿真的函数式编程技术

面向对象编程语言的实践包括函数编程技术的仿真:

  • c ++:函数指针和()运算符的重载。
  • java:匿名类和反思。

粒度不匹配

功能编程和面向对象编程在不同的设计粒度级别上运行:

  • 功能/方法:在小程度上编程。
  • 类/对象/模块:大规模编程。

threre至少有两个问题:

  • 我们在面向对象的编程体系结构中如何定位各个函数的来源?
  • 我们如何将这些单独的函数与面向对象的编程体系结构联系起来?

面向对象的函数式编程构造

c#提供了一个名为delegates的函数编程功能:

delegate string stringfuntype(string s); // declaration

string g1(string s){ // a method whose type matches stringfuntype
  return "some string" + s;
}

stringfuntype f1;    // declaration of a delegate variable
f1 = g1;             // direct method value assignment
f1("some string");   // application of the delegate variable

代表是一流的价值观。这意味着委托类型可以键入方法参数,并且委托可以作为任何其他值的参数传递:

string gf1(stringfuntype f, string s){ [ ... ] } // delegate f as a parameter
console.writeline(gf1(g1, "boo"));   // call

代理可以作为方法的计算返回。例如,假设g是一个string => string类型的方法,并在someclass中实现:

stringfuntype gf2(){ // delegate as a return value
  [ ... ]
  return (new someclass()).g;
}

console.writeline(gf2()("boo")); // call

代表可以进入数据结构:

var l = new linkedlist<stringfuntype>(); // list of delegates
[ ... ]
l.addfirst(g1) ; // insertion of a delegate in the list
console.writeline(l.first.value("boo")); // extract and call

c#代表可能是匿名的:

delegate(string s){ return s + "some string"; };

匿名委托看起来更像lambda表达式:

s => { return s + "some string"; }; 
s => s + "some string";

相互关系函数式编程/面向对象程序设计

扩展方法使程序员能够在不创建新派生类的情况下向现有类添加方法:

static int simplewordcount(this string str){
  return str.split(new char[]{' '}).length;
}

string s1 = "some chain";
s1.simplewordcount(); // usable as a string method
simplewordcount(s1);  // also usable as a standalone method

扩展方法的另一个例子:

static ienumerable<t> mysort<t>(this ienumerable<t> obj) where t:icomparable<t>{
  [ ... ]
}

list<int> somelist = [ ... ];
somelist.mysort();

扩展方法在c#中有严格的限制:

  • 只有静态
  • 不是多态的

c#中的函数式编程集成

c#为arity提供功能和程序通用委托预定义类型,最多16个

delegate tresult func<tresult>();
delegate tresult func<t, tresult>(t a1);
delegate tresult func<t1, t2, tresult>(t1 a1, t2 a2);
delegate void action<t>(t a1);
[ ... ]

委托本身可以包含委托的调用列表。调用此委托时,委托中包含的方法将按它们在列表中出现的顺序调用。结果值由列表中调用的最后一个方法确定。

c#允许将lambda表达式表示为称为表达式树的数据结构:

expression<func<int, int>> expression = x => x + 1;
var d = expression.compile();
d.invoke(2);

因此,它们可以被存储和传输。

功能级别的代码抽象

一个简单的代码:

float m(int y){
  int x1 = [ ... ]; 
  int x2 = [ ... ];
  [ ... ]
  [ ... some code ... ]; // some code using x1, x2 and y
  [ ... ]
}

功能抽象:

public delegate int fun(int x, int y, int z);
float mfun(fun f, int x2, int y){
  int x1 = [ ... ];
  [ ... ]
  f(x1, x2, y);
  [ ... ]
}

int z1 = mfun(f1, 1, 2);
int z2 = mfun(f2, 1, 2);

功能抽象的优点是没有局部重复,并且存在关注点分离。

功能抽象的简单有效应用是对数据的通用高阶迭代操作。

例如,内部迭代器(maps):

ienumerable<t2> map<t1, t2>(this ienumerable<t1> data, func<t1, t2> f){
  foreach(var x in data)
    yield return f(x);
}

somelist.map(i => i * i);

运营组成

在功能编程中,操作组合物很容易。初始代码:

public static void printwordcount(string s){
  string[] words = s.split(' ');

  for(int i = 0; i < words.length; i++)
    words[i] = words[i].tolower();

  var dict = new dictionary<string, int>();

  foreach(var word in words)
    if (dict.containskey(word))
      dict[word]++;
    else 
      dict.add(word, 1);

  foreach(var x in dict)
    console.writeline("{0}: {1}", x.key, x.value.tostring());
}

使用高阶函数的第一个因子

public static void printwordcount(string s){
  string[] words = s.split(' ');
  string[] words2 = (string[]) map(words, w => w.tolower());
  dictionary<string, int> res = (dictionary<string, int>) count(words2);
  app(res, x => console.writeline("{0}: {1}", x.key, x.value.tostring()));
}

使用扩展方法的第二个因子:

public static void printwordcount(string s){
  s
  .split(' ')
  .map(w => w.tolower())
  .count()
  .app(x => console.writeline("{0}: {1}", x.key, x.value.tostring()));
}

我们可以看到代码的可读性增加了。

在c#中,这种操作组合通常与linq一起使用,linq被定义为将编程与关系数据或xml统一起来。下面是一个使用linq的简单示例:

var q = programmers
.where(p => p.age > 20)
.orderbydescending(p => p.age)
.groupby(p => p.language)
.select(g => new { language = g.key, size = g.count(), names = g });

功能部分应用和currying

使用第一类函数,每个n元函数都可以转换为n个一元函数的组合,即成为一个curried函数:

func<int, int, int> lam1 = (x, y) => x + y;
func<int, func<int, int>> lam2 = x => (y => x + y);
func<int, int> lam3 = lam2(3) ; // partial application

柯里:

public static func<t1, func<t2, tres>> curry<t1, t2, tres>(this func<t1, t2, tres> f){
    return (x => (y => f(x, y)));
}
func<int, int> lam4 = lam1.curry()(3); // partial application

面向对象编程中的体系结构功能编程技术

在面向对象编程中具有函数编程功能的一些架构效果:

  1. 减少对象/类定义的数量。
  2. 在函数/方法级别命名抽象。
  3. 操作组合(和序列理解)。
  4. 功能部分应用和currying。

一些经典的面向对象设计模式与功能编程

 

为什么函数式编程通常集成到面向对象的编程中?

主要的面向对象编程语言基于类作为模块:c#,c ++,java。

面向对象编程中开发的强大思想之一:维护,扩展和适应操作可以通过继承和类组合(这避免了对现有代码的任何修改)。函数式编程是这个问题的解决方案。

例如,战略设计模式。

战略

策略模式允许算法独立于使用它的客户端而变化。

C#中面向对象编程中的函数式编程详解

 

策略:只是在方法级别抽象代码的情况(不需要面向对象的封装和新的类层次结构)。例如,在.net framework中:

public delegate int comparison<t>(t x, t y);
public void sort(comparison<t> comparison);

public delegate bool predicate<t>(t obj);
public list<t> findall(predicate<t> match);

C#中面向对象编程中的函数式编程详解

其他设计模式,如命令,观察者,访问者和虚拟代理,可以使一流的功能受益:

C#中面向对象编程中的函数式编程详解

命令

command模式将请求(方法调用)封装为对象,以便可以轻松地传输,存储和应用它们。例如,菜单实现:

public delegate void eventhandler(object sender, eventargs e);
public event eventhandler click;

private void menuitem1_click(object sender, eventargs e){
  openfiledialog fd = new openfiledialog();
  fd.defaultext = "*.*" ; 
  fd.showdialog();
}

public void createmymenu(){
  mainmenu mainmenu1 = new mainmenu();
  menuitem menuitem1 = new menuitem();
  [ ... ]
  menuitem1.click += new eventhandler(menuitem1_click);
}

C#中面向对象编程中的函数式编程详解

观察

对象之间的一对多依赖关系,以便当一个对象更改状态时,将通知并更新其所有依赖项。

C#中面向对象编程中的函数式编程详解

下面是观察者设计模式的经典实现:

public interface observer<s>{
  void update(s s);
}

public abstract class subject<s>{
  private list<observer<s>> _observ = new list<observer<s>>();
  public void attach(observer<s> obs){
    _observ.add(obs);
  }
  public void notify(s s){
    foreach (var obs in _observ)
      obs.update(s);
  }
}

功能编程:

public delegate void updatefun<s>(s s);

public abstract class subject<s>{
  private updatefun<s> _updatehandler;

  public void attach(updatefun<s> f){
    _updatehandler += f;
  }
  public void notify(s s){
    _updatehandler(s);
  }
}

我们可以看到,不需要使用名为update的方法的观察者类。

C#中面向对象编程中的函数式编程详解

虚拟代理

虚拟代理模式:其他对象的占位符,以便仅在需要时创建/计算其数据。

C#中面向对象编程中的函数式编程详解

下面是虚拟代理设计模式的经典实现:

public class simpleproxy : i{
  private simple _simple;
  private int _arg;

  protected simple getsimple(){
    if (_simple == null)
      _simple = new simple(_arg);
    return _simple;
  }
  public simpleproxy(int i){
    _arg = i ;
  }
  public void process(){
    getsimple().process();
  }
}

下面使用函数式编程和懒惰实现虚拟代理设计模式:

public class simplelazyproxy : i{
  private lazy<simple> _simplelazy;

  public simplelazyproxy(int i){
    _simplelazy = new lazy<simple>(() => new simple(i));
  }
  public void process(){
    _simplelazy.value.process();
  }
}

游客

访问者模式允许您定义新操作,而无需更改其操作元素的类。如果没有访问者,则必须单独编辑或派生层次结构的每个子类。访客是许多编程设计问题的关键。

C#中面向对象编程中的函数式编程详解

以下是访问者设计模式的经典实现:

public interface ifigure{
  string getname();
  void accept<t>(ifigurevisitor<t> v);
}

public class simplefigure : ifigure{
  private string _name;

  public simplefigure(string name){ 
    _name = name;
  }
  public string getname(){ 
    return _name;
  }
  public void accept<t>(ifigurevisitor<t> v){
    v.visit(this);
  }
}

public class compositefigure : ifigure{
  private string _name;
  private ifigure[] _figurearray;

  public compositefigure(string name, ifigure[] s){
    _name = name; 
    _figurearray = s;
  }
  public string getname(){
    return _name;
  }
  public void accept<t>(ifigurevisitor<t> v){
    foreach (ifigure f in _figurearray)
      f.accept (v);
    v.visit(this);
  }
}

public interface ifigurevisitor<t>{
  t getvisitorstate();
  void visit(simplefigure f);
  void visit(compositefigure f);
}

public class namefigurevisitor : ifigurevisitor<string>{
  private string _fullname = " ";

  public string getvisitorstate(){
    return _fullname;
  }
  public void visit(simplefigure f){
    _fullname += f.getname() + " ";
  }
  public void visit(compositefigure f){
    _fullname += f.getname() + "/";
  }
}

访客的一些众所周知的弱点:

  • 重构阻力:访客定义取决于其运行的类集。
  • 静态:访问者的实现是静态的(类型安全但灵活性较低)。
  • 入侵:访问者需要客户类预期和/或参与选择正确的方法。
  • 命名不灵活:访问者需要同样命名访问方法的所有不同实现。

尝试使用扩展方法解决访问者问题:

public interface ifigure{
  string getname(); // no accept method required
}
[ ... ]

public static class namefigurevisitor{
  public static void namevisit(this simplefigure f){ 
    _state = f.getname() + " " + _state;
  }
  public static void namevisit(this compositefigure f) {
    _fullname = f.getname() + ":" + _fullname;
    foreach(ifigure g in f.getfigurearray())
      g.namevisit(); // dynamic dispatch required...
    [ ... ]
  }
}

通过函数式编程,visitors可以是函数:

public delegate t visitorfun<v, t>(v f);
public interface ifiguref{
  string getname ();
  t accept<t>(visitorfun<ifiguref, t> v);
}

public class simplefiguref : ifiguref{
  private string _name ;

  public simplefiguref(string name){
    _name = name ;
  }
  public string getname(){
    return _name ; 
  }
  public t accept<t>(visitorfun<ifiguref, t> v){
    return v(this);
  }
}
[...]

public class compositefiguref : ifiguref{
  private string _name;
  private ifiguref[ ] _figurearray;

  public compositefiguref(string name, ifiguref[] s){
    _name = name; 
    _figurearray = s;
  }
  public string getname(){
    return this._name;
  }
  public t accept<t>(visitorfun<ifiguref, t> v){
    foreach(ifiguref f in _figurearray)
      f.accept(v);
    return v(this);
  }
}

C#中面向对象编程中的函数式编程详解

以下简单功能访客:

public static visitorfun<ifiguref, string> makenamefigurevisitorfun(){
    string _state = "";
    return obj => {
      if(obj is simplefiguref)
        _state += obj.getname() + " ";
      else if(obj is compositefiguref)
       _state += obj.getname() + "/";
      return _state ;
   };
}

以数据为导向的访问者:

var dict1 = new dictionary<type, visitorfun<ifiguref, string>>();
dict1.add(typeof(simplefiguref), f => f.getname() + " ");
dict1.add(typeof(compositefiguref), f => f.getname() + "/");

var namefigurefunvisitor1 = makevisitorfun<ifiguref, string>(dict1);

我们可以看到,通过功能编程和数据驱动编程,重构阻力更小,名称刚性更小,静态更少。

加起来

具有函数式编程粒度级别的对象 - 节点编程:

  • 函数式编程适用于模块化对象。
  • 函数/方法级别的代码抽象。
  • 方便的通用迭代器/循环实现。
  • 操作组合,序列/查询理解。
  • 功能部分应用。
  • 对象/类定义数量的限制。
  • 在函数/方法级别命名抽象。
  • 懒惰模拟(在虚拟代理中使用)。
  • 数据驱动编程(在访客中使用)。
  • 架构简化。
  • 增加灵活性。

将函数编程功能添加到面向对象的语言中会带来面向对象编程设计的好处。