Modern C++ 学习笔记——C++函数式编程

本文探讨了Modern C++中的函数式编程,强调了无状态和不可变数据的概念。通过实例展示了如何利用头等函数、map、reduce、filter、pipeline、currying和递归来解决问题。文中还提到了C++17的并行计算支持,以及函数式编程如何提高代码可读性和并行性。
摘要由CSDN通过智能技术生成

往期精彩:


Modern C++ 学习笔记——C++函数式编程

关键字:lambda表达式、函数式编程

函数式编程

在之前的系列文章中介绍过函数对象和lambda表达式,本篇文章就来讲讲它们的主要用途——函数式编程。

什么是函数式编程?

那什么是函数编程呢?它其实来自于数学中的理念.

f(x) = 2x^2 +x+3
g(x) = 3f(x) + 5 = 6x^2 + 3x + 14
h(x) = f(x) + g(x) = 8x^2 + 4x + 17

正如上面的数学函数一样,对于函数式编程,它只关心于定义输入数据和输出数据的关系,在数学表达式中我们称其为输入与输出的一种映射(map),即用函数定义输入数据和输出数据的关系是什么样的。
这样就可以得到关于函数式编程一下特点:

  • 无状态:函数不维护任何状态。函数式编程的核心精神是stateless
  • 不可变数据输入数据不可变,动了输入数据就有危险,所以要返回新的数据集。
    或许这么说有点干燥,为了更好的帮助理解,再举一个最简单的例子:
int copy_add(int x, int y)
{
   
	return x + y;
}
int nocopy_add(int& x, int& y)
{
   
	x += y;
	return x;
}

以上两个函数都实现了对输入的两个int类型值进行相加并且返回的功能,第一个函数式比较纯粹的函数,符合我们上面所说的函数式编程的特点。再看第二个函数,它将入参设为引用(在项目中,为了减少值对象拷贝的性能消耗,常把入参设为引用),这就带来了问题——入参很容易在函数内部被改变。
在著作《Functional Programming in C++》(非常推荐此书)中给出了关于函数式编程的定义:

Functional programming is a style of programming that emphasizes the evaluation of expressions, rather than execution of commands. The expressions in these languages are formed by using functions to combine basic values. A functional language is a language that supports and encourages programming in a functional style.

简单来说:在OOP(面向对象编程)中,正如大多数人做的那样,更多的考虑是算法的步骤,即对对象的处理。而在函数式编程里你需要学会如下的思考方式:什么是输入,什么是输出,还有需要执行哪些转换将两者映射起来

函数式编程

在介绍了函数编程之后,我们尝试使用其思想来解决实际的问题:假如有个vector保存着文件中的所有单词,需要统计其所有单词出现的频率,并且按照评率高低输出对应单词。最传统的命令式编程大概会这么写:

void print_word(vector<string>& words) {
   
    unordered_map<string, int> wordCount;
    for (auto&& s : words) {
   
        unordered_map<string, int>::iterator iter = wordCount.find(s);
        if (iter == wordCount.end()) {
   
            wordCount.insert({
   s, 1});
        } else {
   
            wordCount[s]++;
        }
    }
    vector<pair<int, string>> reverseword;
    for (auto it = wordCount.begin(); it != wordCount.end(); ++it) {
   
        reverseword.emplace_back(make_pair(it->second, it->first));
    }
    sort(reverseword.begin(), reverseword.end(), [](const pair<int, string>& lhs, const pair<int, string>& rhs) {
   
        return lhs.first > rhs.first;
    }); // 高阶函数
    for (auto& p : reverseword) {
   
        cout << "word is " << p
Modern C++ Programming Cookbook by Marius Bancila English | 15 May 2017 | ASIN: B01MQDKPV8 | 590 Pages | AZW3 | 800.97 KB Over 100 recipes to help you overcome your difficulties with C++ programming and gain a deeper understanding of the working of modern C++ About This Book Explore the most important language and library features of C++17, including containers, algorithms, regular expressions, threads, and more, Get going with unit testing frameworks Boost.Test, Google Test and Catch, Extend your C++ knowledge and take your development skills to new heights by making your applications fast, robust, and scalable. Who This Book Is For If you want to overcome difficult phases of development with C++ and leverage its features using modern programming practices, then this book is for you. The book is designed for both experienced C++ programmers as well as people with strong knowledge of OOP concepts. What You Will Learn Get to know about the new core language features and the problems they were intended to solve Understand the standard support for threading and concurrency and know how to put them on work for daily basic tasks Leverage C++'s features to get increased robustness and performance Explore the widely-used testing frameworks for C++ and implement various useful patterns and idioms Work with various types of strings and look at the various aspects of compilation Explore functions and callable objects with a focus on modern features Leverage the standard library and work with containers, algorithms, and iterators Use regular expressions for find and replace string operations Take advantage of the new filesystem library to work with files and directories Use the new utility additions to the standard library to solve common problems developers encounter including string_view, any , optional and variant types In Detail C++ is one of the most widely used programming languages. Fast, efficient, and flexible, it is used to solve many problems. The latest versions of C++ have seen programmers change the way they code, giving up on the old-fashioned C-style programming and adopting modern C++ instead. Beginning with the modern language features, each recipe addresses a specific problem, with a discussion that explains the solution and offers insight into how it works. You will learn major concepts about the core programming language as well as common tasks faced while building a wide variety of software. You will learn about concepts such as concurrency, performance, meta-programming, lambda expressions, regular expressions, testing, and many more in the form of recipes. These recipes will ensure you can make your applications robust and fast. By the end of the book, you will understand the newer aspects of C++11/14/17 and will be able to overcome tasks that are time-consuming or would break your stride while developing. Style and approach This book follows a recipe-based approach, with examples that will empower you to implement the core programming language features and explore the newer aspects of C++.
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值