问题描述
到目前为止,我主要接触 OO 编程,并期待学习一门函数式语言.我的问题是:
I've been mainly exposed to OO programming so far and am looking forward to learning a functional language. My questions are:
- 什么时候选择函数式编程而不是面向对象?
- 在哪些典型问题定义中函数式编程是更好的选择?
推荐答案
当您预期不同类型的软件进化时:
When you anticipate a different kind of software evolution:
当您对事物有一组固定的操作,并且随着代码的发展,您主要添加新事物时,面向对象的语言是很好的.这可以通过添加实现现有方法的新类来实现,现有的类保持不变.
Object-oriented languages are good when you have a fixed set of operations on things, and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone.
当您拥有一组固定的事物时,函数式语言是很好的,并且随着您的代码的发展,您主要在现有事物上添加新的操作.这可以通过添加使用现有数据类型计算的新函数来实现,而现有函数则保持不变.
Functional languages are good when you have a fixed set of things, and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone.
当进化走错路时,你就会遇到问题:
When evolution goes the wrong way, you have problems:
向面向对象的程序添加新操作可能需要编辑许多类定义以添加新方法.
Adding a new operation to an object-oriented program may require editing many class definitions to add a new method.
向函数式程序添加一种新事物可能需要编辑许多函数定义以添加新案例.
Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.
这个问题已经众所周知很多年了;1998 年,Phil Wadler 将其称为表达问题".虽然一些研究人员认为表达问题可以通过诸如 mixin 等语言特性来解决,但尚未有一个被广泛接受的解决方案成为主流.
This problem has been well known for many years; in 1998, Phil Wadler dubbed it the "expression problem". Although some researchers think that the expression problem can be addressed with such language features as mixins, a widely accepted solution has yet to hit the mainstream.
在哪些典型问题定义中函数式编程是更好的选择?
函数式语言擅长以树的形式处理符号数据.一个最喜欢的例子是编译器,其中源语言和中间语言很少改变(大部分是相同的事物),但编译器作者总是添加新的翻译和代码改进或优化(对事物的新操作).编译和翻译通常是函数式语言的杀手级应用".
Functional languages excel at manipulating symbolic data in tree form. A favorite example is compilers, where source and intermediate languages change seldom (mostly the same things), but compiler writers are always adding new translations and code improvements or optimizations (new operations on things). Compilation and translation more generally are "killer apps" for functional languages.
这篇关于函数式编程与面向对象编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!