我读过维基百科上关于响应式编程的文章。我还读过一篇关于函数式响应式编程的小文章。这些描述相当抽象。

函数式响应式编程(FRP)在实践中意味着什么? 反应式编程(相对于非反应式编程?)由什么组成?

我的背景是命令式/OO语言,所以与此范例相关的解释将受到赞赏。


当前回答

免责声明:我的答案是在rx.js的上下文中给出的——一个用于Javascript的“响应式编程”库。

在函数式编程中,不是遍历集合的每个项,而是对集合本身应用高阶函数(hof)。因此,FRP背后的思想是,与其处理每个单独的事件,不如创建一个事件流(使用可观察对象*实现),并对其应用HoFs。通过这种方式,您可以将系统可视化为连接发布者和订阅者的数据管道。

The major advantages of using an observable are: i) it abstracts away state from your code, e.g., if you want the event handler to get fired only for every 'n'th event, or stop firing after the first 'n' events, or start firing only after the first 'n' events, you can just use the HoFs (filter, takeUntil, skip respectively) instead of setting, updating and checking counters. ii) it improves code locality - if you have 5 different event handlers changing the state of a component, you can merge their observables and define a single event handler on the merged observable instead, effectively combining 5 event handlers into 1. This makes it very easy to reason about what events in your entire system can affect a component, since it's all present in a single handler.

可观察对象是可迭代对象的对偶。

Iterable是一个惰性消费序列——迭代器在需要使用每个项时都会拉出它,因此枚举是由消费者驱动的。

可观察对象是一个惰性生成的序列——每一项在被添加到序列时都被推送给观察者,因此枚举是由生产者驱动的。

其他回答

关于响应式编程的简短而清晰的解释出现在Cyclejs -响应式编程中,它使用了简单和可视化的示例。

一个[模块/组件/对象]是反应性的意味着它是完全负责的 通过对外部事件的反应来管理自己的状态。 这种方法的好处是什么?这就是控制反转, 主要是因为[module/Component/object]对自己负责,使用私有方法来改进封装。

这是一个很好的起点,而不是一个完整的知识来源。从那里你可以跳到更复杂和更深入的文件。

免责声明:我的答案是在rx.js的上下文中给出的——一个用于Javascript的“响应式编程”库。

在函数式编程中,不是遍历集合的每个项,而是对集合本身应用高阶函数(hof)。因此,FRP背后的思想是,与其处理每个单独的事件,不如创建一个事件流(使用可观察对象*实现),并对其应用HoFs。通过这种方式,您可以将系统可视化为连接发布者和订阅者的数据管道。

The major advantages of using an observable are: i) it abstracts away state from your code, e.g., if you want the event handler to get fired only for every 'n'th event, or stop firing after the first 'n' events, or start firing only after the first 'n' events, you can just use the HoFs (filter, takeUntil, skip respectively) instead of setting, updating and checking counters. ii) it improves code locality - if you have 5 different event handlers changing the state of a component, you can merge their observables and define a single event handler on the merged observable instead, effectively combining 5 event handlers into 1. This makes it very easy to reason about what events in your entire system can affect a component, since it's all present in a single handler.

可观察对象是可迭代对象的对偶。

Iterable是一个惰性消费序列——迭代器在需要使用每个项时都会拉出它,因此枚举是由消费者驱动的。

可观察对象是一个惰性生成的序列——每一项在被添加到序列时都被推送给观察者,因此枚举是由生产者驱动的。

它是关于随着时间(或忽略时间)的数学数据转换。

在代码中,这意味着函数的纯洁性和声明性编程。

状态错误是标准命令式范例中的一个大问题。不同的代码位可能在程序执行的不同“时间”改变一些共享状态。这很难处理。

在FRP中,你描述了(就像在声明式编程中一样)数据如何从一种状态转换到另一种状态,以及触发它的是什么。这允许您忽略时间,因为您的函数只是对其输入作出反应,并使用它们的当前值创建一个新值。这意味着状态包含在转换节点的图(或树)中,并且在功能上是纯的。

这大大降低了复杂性和调试时间。

想想数学中的A=B+C和程序中的A=B+C之间的区别。 在数学中,你描述的是一种永不改变的关系。在一个程序中,它说“现在”a是B+C。但是下一个命令可能是b++,在这种情况下A不等于B+C。在数学或声明性编程中,A总是等于B+C,无论你在什么时候问。

因此,通过消除共享状态的复杂性并随时间改变值。你的程序更容易推理。

EventStream是一个EventStream +一些转换函数。

行为是一个EventStream +内存中的某个值。

当事件触发时,通过运行转换函数更新值。这产生的值存储在行为内存中。

行为可以被组合以产生新的行为,这些行为是对N个其他行为的转换。该组合值将在输入事件(行为)触发时重新计算。

由于观察器是无状态的,我们经常需要几个观察器来模拟一个状态机,就像在拖动示例中那样。我们必须保存所有相关观察者都可以访问的状态,比如上面的变量路径。”

引用自-弃用观察者模式 http://infoscience.epfl.ch/record/148043/files/DeprecatingObserversTR2010.pdf

Andre Staltz的这篇文章是迄今为止我所见过的最好、最清楚的解释。

以下是文章中的一些引述:

响应式编程是使用异步数据流进行编程。 最重要的是,你会得到一个神奇的功能工具箱来组合、创建和过滤任何这些流。

下面是文章中精彩图表的一个例子:

伙计,这主意太棒了!为什么1998年的时候我没有发现?总之,这是我对Fran教程的理解。建议是最受欢迎的,我正在考虑开始一个基于此游戏引擎。

import pygame
from pygame.surface import Surface
from pygame.sprite import Sprite, Group
from pygame.locals import *
from time import time as epoch_delta
from math import sin, pi
from copy import copy

pygame.init()
screen = pygame.display.set_mode((600,400))
pygame.display.set_caption('Functional Reactive System Demo')

class Time:
    def __float__(self):
        return epoch_delta()
time = Time()

class Function:
    def __init__(self, var, func, phase = 0., scale = 1., offset = 0.):
        self.var = var
        self.func = func
        self.phase = phase
        self.scale = scale
        self.offset = offset
    def copy(self):
        return copy(self)
    def __float__(self):
        return self.func(float(self.var) + float(self.phase)) * float(self.scale) + float(self.offset)
    def __int__(self):
        return int(float(self))
    def __add__(self, n):
        result = self.copy()
        result.offset += n
        return result
    def __mul__(self, n):
        result = self.copy()
        result.scale += n
        return result
    def __inv__(self):
        result = self.copy()
        result.scale *= -1.
        return result
    def __abs__(self):
        return Function(self, abs)

def FuncTime(func, phase = 0., scale = 1., offset = 0.):
    global time
    return Function(time, func, phase, scale, offset)

def SinTime(phase = 0., scale = 1., offset = 0.):
    return FuncTime(sin, phase, scale, offset)
sin_time = SinTime()

def CosTime(phase = 0., scale = 1., offset = 0.):
    phase += pi / 2.
    return SinTime(phase, scale, offset)
cos_time = CosTime()

class Circle:
    def __init__(self, x, y, radius):
        self.x = x
        self.y = y
        self.radius = radius
    @property
    def size(self):
        return [self.radius * 2] * 2
circle = Circle(
        x = cos_time * 200 + 250,
        y = abs(sin_time) * 200 + 50,
        radius = 50)

class CircleView(Sprite):
    def __init__(self, model, color = (255, 0, 0)):
        Sprite.__init__(self)
        self.color = color
        self.model = model
        self.image = Surface([model.radius * 2] * 2).convert_alpha()
        self.rect = self.image.get_rect()
        pygame.draw.ellipse(self.image, self.color, self.rect)
    def update(self):
        self.rect[:] = int(self.model.x), int(self.model.y), self.model.radius * 2, self.model.radius * 2
circle_view = CircleView(circle)

sprites = Group(circle_view)
running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
        if event.type == KEYDOWN and event.key == K_ESCAPE:
            running = False
    screen.fill((0, 0, 0))
    sprites.update()
    sprites.draw(screen)
    pygame.display.flip()
pygame.quit()

简而言之:如果每个组成部分都可以被视为一个数字,那么整个系统就可以被视为一个数学方程,对吗?