ReactiveCocoa (1) Functional Reactive Programming

前端之家收集整理的这篇文章主要介绍了ReactiveCocoa (1) Functional Reactive Programming前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


Functional Reactive Programming (简称FRP)


目前,大部分程序员编程的模式都是属于imperative programming (命令式编程)。这种模式的特点是:

This paradigm relies on programmers to think about how they want their programs to accomplish these tasks: developers write many instructions that modify the program’s state. If the programmer writes the correct instructions in the correct order,then the program’s output will correctly accomplish its task.

(译注:命令式编程的特点是程序员专注于要完成的编程任务,通过编写程序指令来表征程序的不同状态,这些正确的指令序列运行得到正确的结果。)


显然,这种命令式的编程模式过多的关注了任务实现的细节,而导致了臃肿和烦人;那么将应运而生了另一种编程模式:Declarative Programming(前者关注的是how to accomplish,而后者关注的是whatto accomplish)。

了解一下什么是Declarative Programming:

From Wikipedia:
Declarative programming is a non-imperative style of programming in which programs describe their desired results without explicitly listing commands or steps that must be performed. Functional and logical programming languages are characterized by a declarative programming style.


Functional Reactive Programming 属于 Declarative Programming。

Functional Reactive Programming is a paradigm that is a combination of two declarative sub- paradigms: functional and reactive.


1.Functional Programming

Functional programming is about treating functions asfirst- class objects within your language.
注解:在Functional programming中,是将函数作为first- class object(第一类对象)。那么“第一类对象”是什么意思呢?这表示函数与其他传统类型的对象具有相同的权利。例如可以存储到某个变量中,或者可以作为实参传递给其他函数,或者作为其他函数的返回值等。(Lua语言中的函数就有这样的特性)


There is no mutable state in functional programming. A function,f,always yields the same output given the same input. Always.

注解:在 Functional programming 中,是不存在可变状态的,也就是说对于某一个函数,相同的输入必定是导致相同的输出



2.Reactive Programming:“Programming around data flows and the propagation of change”

先看一段代码


如果使用FRP,c的值将会随着b的值改变而改变,所以叫做“响应式编程”。

比较直观的例子就是Excel,当改变某一个单元格的内容时,该单元格相关的计算结果也会随之改变。

FRP提供了一种信号机制来实现这样的效果,通过信号来记录值的变化。

信号可以被叠加、分割或合并。通过对信号的组合,就不需要去监听某个值或事件。




总结:

• We’re here to learn functional reactive programming so we can be more efficient.
• Declarative programming frees us from having to think about how to accomplish tasks and
lets us focus only on the tasks themselves.
• Functional reactive programming is the marriage of functional and reactive programming.


使用FRP主要有两个好处:直观和灵活。直观的代码容易编写、阅读和维护,灵活的特性便于应对变态的需求。

猜你在找的React相关文章