易语言能不能做到c语言_用c的功能方式做到这一点

易语言能不能做到c语言

I’ve spent some time with C++ for doing Competitive Programming in my graduation days. But I never got a chance to use C++ in my office projects, I was coding in Functional programming(FP) languages. But after 2 years, I got an opportunity to work on C++. As a Functional Programming enthusiast who is very much habituated to the cool FP style which makes the life of developers easy, I started exploring ways to code in FP style in C++. I learnt C++ has got amazing features in the latest releases. In this blog, we will go through the basics of functional programming, and what parts of it are possible in C++.

在毕业的日子里,我花了一些时间在C ++上做竞争性编程。 但是我从来没有机会在我的办公项目中使用C ++,而是用功能编程(FP)语言进行编码。 但是两年后,我有机会从事C ++工作。 作为一个非常喜欢凉爽的FP风格(使开发人员的工作变得轻松)的函数式编程爱好者,我开始探索在C ++中以FP风格进行编码的方法。 我了解到C ++在最新版本中具有惊人的功能。 在此博客中,我们将介绍函数式编程的基础知识,以及在C ++中可能实现的哪些部分。

先决条件: (Prerequisites:)

  • A little experience in C++

    一点C ++经验
  • A bit of experience with any Functional programming language or paradigm

    具备任何函数式编程语言或范例的经验
  • A C++ compiler which supports C++11 standard

    支持C ++ 11标准的C ++编译器

让我们开始吧 (Let’s get started)

Functional programming is a declarative type of programming style. Its sole focus is on “what to solve” in contrast to an imperative style where the main focus is on “how to solve“. It uses expressions instead of statements.

函数式编程是一种声明式的编程风格。 与命令式风格相比,它的唯一重点是“ 解决什么 ”,而命令式风格则将重点放在“ 如何解决 ”上。 它使用表达式而不是语句。

功能编程关键概念 (Functional Programming Key Concepts)

  • Functions as first class objects

    用作一流对象
  • Pure functions

    纯功能

功能性编程规则 (Functional Programming Rules)

  • Immutable variables: In functional programming, you can’t modify a variable after it’s been initialized. You just can’t. You can create new variables but you can’t modify existing variables.

    不可变的变量 :在函数式编程中,您无法在变量初始化后对其进行修改。 你就是不行 您可以创建新变量,但不能修改现有变量。

  • No side effects: A side effect is a state change in something other than the function that’s currently executing. Modifying a variable defined outside the function, printing out to the console, raising an exception, and reading data from a file are all examples of side effects.

    无副作用 :副作用是状态变化,而不是当前正在执行的功能。 修改函数外部定义的变量,输出到控制台,引发异常以及从文件读取数据都是副作用的示例。

  • No state: A function may have local variables containing temporary state internally, but the function cannot reference any member variables of the class or object the function belongs to. State encourages mutability leading to side effects. Functional Programming doesn’t want you to do that.

    无状态:一个函数可能具有内部包含临时状态的局部变量,但是该函数不能引用该函数所属的类或对象的任何成员变量。 国家鼓励易变性导致副作用。 函数式编程不希望您那样做。

These are a few key concepts, rules of FP. Even if you do not follow all of these rules all the time, you can still benefit from the FP ideas in your applications. Anyways, C++ was never meant to be a strict or pure functional programming language. To be honest, functional programming is not the right tool for every problem(Yeah! It’s my opinion. It might change in future. Opinions do change with experience!). For now, let’s learn what problems FP is good at solving.

这些是FP的一些关键概念,即规则。 即使您始终不遵循所有这些规则,您仍然可以从应用程序中的FP创意中受益。 无论如何,C ++绝不是要成为严格或纯函数式编程语言。 老实说,函数式编程并不是解决每个问题的正确工具(是的!这是我的观点。将来可能会有所改变。观点会随着经验而改变!)。 现在,让我们学习FP擅长解决哪些问题。

用作一流对象 (Functions as first class objects)

In the functional programming world, functions are first-class objects. Functions are treated like any other variable. For example, a function can be passed as an argument to other functions and can be assigned as a value to a variable.

在函数式编程世界中,函数是一流的对象。 函数与其他任何变量一样对待。 例如,一个函数可以作为参数传递给其他函数,也可以作为值分配给变量。

In C++, functions are not first class objects. The closest we get is lambda expressions.

在C ++中,函数不是一流的对象。 我们得到的最接近的是lambda表达式。

auto printText = [](std::string text) { std::cout << text << std::endl; };

Above code is creating a lambda printText, which takes a single parameter text , prints it and returns nothing. The [] brackets are used to specify the closure for the function. More information about lambdas can be found here.

上面的代码创建了一个lambda printText ,它接受一个参数text ,将其打印,但不返回任何内容。 []括号用于指定函数的闭包。 有关lambda的更多信息,请参见此处

Let’ see how we can do FP by looking at how we can apply different combinators like filter, map, reduce on C++ vector or any collection. Let’s take the below vector:

通过查看如何应用不同的组合器(如过滤器,映射,C ++向量上的reduce或任何集合),来了解如何实现FP。 让我们采用以下向量:

std::vector<std::string> messages = { "Hello Pal", "How are you?", "I'm still coding in C++" };

for_each (for_each)

std::for_each(messages.begin(), messages.end(), printText);

First two parameters are starting and ending of the collection. Then the third parameter we pass is a unary lambda which operates on each element.

前两个参数是集合的开始和结束。 然后,我们传递的第三个参数是对每个元素进行操作的一元lambda。

Let’s create a vector of custom student objects and apply the combinators on it.

让我们创建一个自定义学生对象的向量,并在其上应用组合器。

class Student
{
public:
string _name;
int _score;
Student(string name, int score)
{
_name = name;
_score = score;
}
void incrementScore() {
_score += 1;
}
string name()
{
return _name;
}
int score()
{
return _score;
}
};
std::vector<Student> students = {Student("Alice", 85), Student("Bob", 62), Student("Charlie", 81), Student("Jack", 90), Student("Jimmy", 40), Student("Sherlock", 67),};

Assume, you’re the teacher and want to print their details. Then, you can use for_each to print their details.

假设您是老师,想打印他们的详细信息。 然后,您可以使用for_each打印其详细信息。

auto printStudentDetails = [](Student student) { std::cout << student.name() << " " << student.score() << std::endl; };std::for_each(students.begin(), students.end(), printStudentDetails);

In the above code, we have used a printing lambda to print each student’s detail.

在上面的代码中,我们使用了打印lambda来打印每个学生的详细信息。

地图 (map)

In C++, the equivalent for the functional map is transform. Assume, You gave a one mark question with insufficient/invalid data and want to add one mark to every student. Then you can use transform to update every student’s score.

在C ++中,功能map的等效项是transform 。 假设,您提出了一个分数不足或无效数据的问题,并想为每个学生加一个分数。 然后,您可以使用transform更新每个学生的分数。

auto addOne = [](Student student) { student.incrementScore(); return student; };
std::transform(students.begin(), students.end(), students.begin(), addOne);

You’ll have to provide the begin, end pointers of the input collection, the begin pointer of the output collection and the operation. You can even perform transform on two collections at once. You can check it out, it’s out of the scope of this blog.

您必须提供输入集合的开始,结束指针,输出集合的开始指针和操作。 您甚至可以一次对两个集合执行transform 。 您可以检查出来,这超出了本博客的范围。

过滤 (filter)

In C++, the functional filter has many equivalents based on the use-case. If you just want to get a copy of elements with specific properties, you can use copy_if. Anyhow, there are other functions like remove_if, find_if, etc too. And each such function has a “not” alternate as well like copy_if_not, find_if_not, etc.

在C ++中,基于用例,功能filter具有许多等效项。 如果只想获取具有特定属性的元素的副本,则可以使用copy_if 。 无论如何,还有其他功能,例如remove_iffind_if等。 每个此类函数都有一个“ not ”替代项,例如copy_if_notfind_if_not等。

auto aboveEighty = [](Student student) { return student.score() > 80; };
vector<Student> topStudents = {};
auto it = std::copy_if(students.begin(), students.end(), back_inserter(topStudents), aboveEighty);
std::for_each(topStudents.begin(), topStudents.end(), printStudentDetails);

The syntax for copy_if is: copy_if(Iterator inputBegin, Iterator inputEnd, Iterator outputBegin, predicate). You’ll have to provide the begin, end pointers of the input collection, the begin pointer of the output collection and the operation. I’ve used back_inserter_iterator instead of outputBegin which enables me to push the elements into topStudents vector without needing to initialize the vector.

的语法copy_if是: copy_if(Iterator inputBegin, Iterator inputEnd, Iterator outputBegin, predicate) 。 您必须提供输入集合的开始,结束指针,输出集合的开始指针和操作。 我使用了back_inserter_iterator而不是outputBegin,这使我可以将元素推入topStudents向量,而无需初始化向量。

缩小或折叠 (Reduce or Fold)

The functional reduce equivalent in C++ is accumulate. Assume you’ve a vector with numbers and you want to sum them all.

功能reduce用C ++当量是accumulate 。 假设您有一个带有数字的向量,并且想将它们全部加起来。

vector<int> numbers{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << std::accumulate(numbers.begin(), numbers.end(), 0,
[](int first, int second) { return first + second; });

You’ll have to provide the begin, end pointers of the input collection, the initial value of the accumulator and a binary lambda. Accumulator can also be applied to our custom students vector. Below code calculates the average score of the classroom.

您必须提供输入集合的开始,结束指针,累加器的初始值和二进制lambda。 累加器也可以应用于我们的自定义学生矢量。 下面的代码计算教室的平均分数。

auto binaryOp = [](int score, Student student) { return score + student.score(); };
std::cout << std::accumulate(students.begin(), students.end(), 0, binaryOp)/students.size();

纯函数 (Pure Functions)

A function is a pure function if:

在以下情况下,函数是纯函数:

  • The execution of the function has no side effects.

    该功能的执行没有副作用。
  • The return value of the function depends only on the input parameters passed to the function.

    函数的返回值仅取决于传递给函数的输入参数。
int sum(int a, int b){
return a+b;
}

Above created function is a pure function. Many in-built C++ functions are pure like min, max, strlen, etc. You can write functions which accept all const parameters and don’t change the instance variables. In GCC, you can even mark functions as pure using the “pure” attribute which enables better optimization. If a function is known as pure to the compiler then Loop optimization and subexpression elimination can be applied to it. But C++ allows side-effects, mutability as well by default.

上面创建的函数是纯函数。 许多内置的C ++函数是纯函数,例如min,max,strlen等。您可以编写接受所有const参数且不更改实例变量的函数。 在GCC中,您甚至可以使用“ pure ”属性将函数标记为pure,从而实现更好的优化。 如果编译器将某个函数称为纯函数,则可以对其进行循环优化子表达式消除 。 但是C ++默认情况下也具有副作用,可变性。

public class NonPureFunctionAndMutatingParametersExample{
private int total= 0;
public int add(int nextValue) {
this.total+= nextValue;
return this.total;
}
public void incrementScore(Student &student){
student.score += 1;
}
}

In the above code:

在上面的代码中:

  • add method is changing the state

    添加方法正在改变状态
  • incrementScore method is changing the function parameters

    IncrementScore方法正在更改函数参数

We should avoid doing the above things unless necessary. Yes, there are cases where side effects, mutability would benefit.

除非必要,我们应该避免做上述事情。 是的,在某些情况下,副作用和可变性会受益。

The rule Immutable variables is a good practice to follow. Once you create a variable and set its value, you can have full confidence knowing that the value of that variable will never change but sometimes it is not suitable. If you’re building an application which has to run in the end-users low configuration machines, then you’ll have limited memory, time. In such cases, it’s suggested to accept the references/pointers of the parameters, mutate them to save memory and copying time.

不可变变量规则是遵循的好习惯。 创建变量并设置其值后,您便可以完全放心,该变量的值将永远不会改变,但有时并不适用。 如果要构建必须在最终用户配置较低的计算机上运行的应用程序,则时间和内存将有限。 在这种情况下,建议接受参数的引用/指针,对其进行更改以节省内存和复制时间。

The rule No side effects is very helpful. It gives confidence that this function won’t affect the outside world and it’s safe to call it anywhere. But it makes it hard in some scenarios e.g. writing to a database (that is a side effect).

没有副作用的规则非常有帮助。 它使人确信该功能不会影响外界,因此可以在任何地方调用它。 但是,在某些情况下(例如,写入数据库),这会很困难(这是副作用)。

There are some other concepts, rules like Higher order functions, recursion over loop, etc which can be applied whenever needed.

还有其他一些概念,规则,例如高阶函数,循环递归等,可以在需要时应用。

结论 (Conclusion)

As I said earlier, Functional Programming is an amazing paradigm but there are scenarios where not abiding a few rules of it gives optimal solutions.

正如我之前说的,函数式编程是一个了不起的范例,但是在某些情况下,不遵守其中的一些规则可以提供最佳解决方案。

C++ has changed a lot in the last few years. The new constructs make it an amazing tool to build any kind of applications. It’s no more just C with Classes. Happy Coding!!!

在过去的几年中,C ++发生了很大变化。 新的构造使其成为构建任何类型的应用程序的绝佳工具。 不再只是 带有Class的C了 。 快乐编码!

翻译自: https://medium.com/swlh/doing-it-the-functional-way-in-c-5c392bbdd46a

易语言能不能做到c语言

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值