Functional Programming

本文介绍如何利用C# 2.0的泛型和匿名委托特性来实现函数式编程,通过具体示例展示了如何简化集合操作,提高代码可读性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.host01.com/article/Net/c/056609494811175.htm

Functional Programming
Functional Programming 不是一个新鲜的概念了,例如 C++ 虽然不是一门 Functional Programming 语言,但对它也有变通的支持——通过使用模板,函数对象(Function Objects)和运算符重载等手段,STL、Boost 等库提供了巧妙无比的、高性能的算法和功能。长久以来似乎 C++ 能实现的这些特性对于诸如 Java 和 C# 这些强调类型安全的面向对象的编程语言和框架来说是绝缘的。现在,在 CLR 范型和 C# 2.0 匿名委托的支持下,我们也可以构造令人吃惊的 Functional Programming 程序了,而且比 C++ 更加简单(当然性能无法相比,因为 CLR 中的范型是一种运行时技术,而 C++ 中的模板则是编译时技术)。当前 .NET BCL 对 Functional Programming 的支持限于集合类,确切说是 List<T> 和 Array。

我们来看一个简单的例子。假设有一个联系人列表 List<Contact>,联系人的定义如下:



class Contact {

public string Name;

...

}



现在我们要把这个列表中所有联系人的姓名拷贝到另外一个列表。你可能马上就动手写了出来:



List<Contact> c1 = ...;

List<string> c2 = new List<string>();



foreach (Contact c in c1) {

c2.Add(c.Name);

}



这是一段非常规矩的 C# 代码。在 .NET 2.0 中,有了范型和匿名委托,我们可以写出如下的完成相同功能的实现:



List<Contact> c1 = ...;

List<string> c2 = c1.ConvertAll<string>(

delegate(Contact c) { return c.Name; } );



显然这段代码比手工编写的 foreach 代码更简捷,在表达意图方面也显得更加清楚和直接。其中 ConvertAll 方法是一个范型方法,作用是将列表元素转换为指定类型的列表。原型为:



List<U> ConvertAll<U>(Converter<T, U> converter);



Converter<T, U> 是一个范型委托,指定了如何进行转换(类似 C++ 中的函数对象),原型为(T 为原始类型,U 为目标类型):



delegate U Converter<T, U>(T from);



这里只是举了一个简单的例子,对于更复杂的情况,范型和匿名委托允许你用更富想象力的方法去实现(例如,匿名委托允许你引用栈上的变量)。

下面是 BCL 中的用于Functional Programming的范型委托(位于 System 命名空间中):



原型
描述

delegate bool Predicate<T>(T obj);
访问集合时,对指定元素的断言(true 或 false)

delegate void Action<T>(T obj);
访问集合时,对指定元素做出特定动作

delegate int Comparison<T>(T x, T y);
比较两个元素

delegate U Converter<T, U>(T from);
把一个元素转换为另外一个,用于在两个集合之间拷贝元素




List<T> 提供了如下支持 Functional Programming 的方法:



原型
描述

int FindIndex(Predicate<T> match);

int FindIndex(int index, Predicate<T> match);

int FindIndex(int index, int count, Predicate<T> match);
找出第一个满足断言条件的元素的索引

int FindLastIndex(Predicate<T> match);

int FindLastIndex(int index, Predicate<T> match);

int FindLastIndex(int index, int count, Predicate<T> match);
找出最后一个满足断言条件的元素的索引

List<T> FindAll(Predicate<T> match);
找出所有满足断言条件的元素

Nullable<T> Find(Predicate<T> match);
找出第一个满足断言条件的元素

Nullable<T> FindLast(Predicate<T> match);
找出最后一个满足断言条件的元素

bool Exists(Predicate<T> match);
判断满足断言条件的元素是否存在

bool TrueForAll(Predicate<T> match);
判断是否所有的元素都满足断言条件

int RemoveAll(Predicate<T> match);
删除所有满足断言条件的元素,返回删除的元素数

void ForEach(Action<T> action);
类似 foreach 语句

void Sort(Comparison<T> comparison);
排序

List<U> ConvertAll(Converter<T, U> converter);
转换集合元素




Array 类提供了类似的支持 Functional Programming 的方法,不同之处在于它们都是类方法而非实例方法,在此限于篇幅不再列举。下面我们来看看前面那个例子换成数组的话是什么样子:



Contact[] contacts = ...;

string[] names = Array.ConvertAll<Contact, string>(contacts,

delegate(Contact c) { return c.Name; } );

Learning C++ Functional Programming by Wisnu Anggoro English | 10 Aug. 2017 | ISBN: 1787281973 | ASIN: B06WVD7CVT | 304 Pages | AZW3 | 2.4 MB Key Features Modularize your applications and make them highly reusable and testable Get familiar with complex concepts such as metaprogramming, concurrency, and immutability A highly practical guide to building functional code in C++ filled with lots of examples and real-world use cases Book Description Functional programming allows developers to divide programs into smaller, reusable components that ease the creation, testing, and maintenance of software as a whole. Combined with the power of C++, you can develop robust and scalable applications that fulfill modern day software requirements. This book will help you discover all the C++ 17 features that can be applied to build software in a functional way. The book is divided into three modules—the first introduces the fundamentals of functional programming and how it is supported by modern C++. The second module explains how to efficiently implement C++ features such as pure functions and immutable states to build robust applications. The last module describes how to achieve concurrency and apply design patterns to enhance your application's performance. Here, you will also learn to optimize code using metaprogramming in a functional way. By the end of the book, you will be familiar with the functional approach of programming and will be able to use these techniques on a daily basis. What you will learn Get to know the difference between imperative and functional approaches See the use of first-class functions and pure functions in a functional style Discover various techniques to apply immutable state to avoid side effects Design a recursive algorithm effectively Create faster programs using lazy evaluation Structure code using design patterns to make the design process easier Use concurrency techniques to develop responsive software Learn how to use the C++ Standard Template Library and metaprogramming in a functional way to improve code optimization About the Author Wisnu Anggoro is a Microsoft Certified Professional in C# programming and an experienced C/C++ developer. He has also authored the books Boost.Asio C++ Network Programming - Second Edition and Functional C# by Packt. He has been programming since he was in junior high school, which was about 20 years ago, and started developing computer applications using the BASIC programming language in the MS-DOS environment. He has solid experience in smart card programming, as well as desktop and web application programming, including designing, developing, and supporting the use of applications for SIM Card Operating System Porting, personalization, PC/SC communication, and other smart card applications that require the use of C# and C/C++. He is currently a senior smart card software engineer at CIPTA, an Indonesian company that specializes in innovation and technology for smart cards. He can be reached through his email at wisnu@anggoro.net. Table of Contents Diving into Modern C++ Manipulating functions in functional programming Applying immutable state to the function Recurring method invocation using recursive algorithm Procrastinating the execution process using Lazy Evaluation Optimizing code with Metaprogramming Running parallel execution using Concurrency Creating and debugging application in functional approach
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值