Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 函数式编程小结 #18

Open
sweeetcc opened this issue Mar 1, 2017 · 0 comments
Open

JavaScript 函数式编程小结 #18

sweeetcc opened this issue Mar 1, 2017 · 0 comments
Assignees
Labels

Comments

@sweeetcc
Copy link
Owner

sweeetcc commented Mar 1, 2017

JavaScript 函数式编程小结

为了彻底理解 redux 里面的一些相关概念,看了一下函数式编程相关的东西,摘录总结如下:

纯函数

定义:

纯函数式这样一种函数,即相同的输入,永远会得到相同的输出,而且没有任何可观察的副作用。

举例:

slice 和 splice 这两个函数的作用方式大不相同,slice 并不会修改原数组,而 splice 则不然。

比如:

const arr = [1, 2, 3, 4, 5];
arr.slice(1, 3);
console.log(arr);
arr.slice(1, 3);
console.log(arr);
arr.slice(1, 3);
console.log(arr);

75f836f9-5566-4aae-8800-efb12f073c72

const arr = [1, 2, 3, 4, 5];
arr.splice(1, 3);
console.log(arr);
arr.splice(1, 3);
console.log(arr);
arr.splice(1, 3);
console.log(arr);

01e64748-f20c-4dce-bf1c-bc289f413e6d

通过结果可以看到,slice 并不会修改原数组,所以是没有“副作用”的函数,而 splice 则是会更改原数组的。

副作用:

副作用是在计算结果过程中,系统状态的一种变化,或者与外部世界进行的可观察的交互。

副作用可能包括:

  • 更改文件系统
  • 向数据库插入纪录
  • 发送 HTTP 请求
  • 可变数据
  • 打印 log
  • 获取用户输入
  • DOM 查询
  • 访问文件系统

函数:

函数只是两种数值之间的关系:每个输入值返回且仅返回一个输出值。

使用纯函数的理由:

可缓存(Cacheable):

纯函数总是能够根据输入来做缓存。因为前提是提供相同的输入总是有相同的输出,所以能够缓存。

可移植 / 自文档化 (Portable / Self-Documenting)

函数的依赖需要明确,以便于观察和理解,通过其依赖(参数)就能够知道它的目的。

比如:

// 不纯的
var signUp = function(attrs) {
  var user = saveUser(attrs);
  welcomeUser(user);
};

var saveUser = function(attrs) {
    var user = Db.save(attrs);
    ...
};

var welcomeUser = function(user) {
    Email(user, ...);
    ...
};

// 纯的
var signUp = function(Db, Email, attrs) {
  return function() {
    var user = saveUser(Db, attrs);
    welcomeUser(Email, user);
  };
};

var saveUser = function(Db, attrs) {
    ...
};

var welcomeUser = function(Email, user) {
    ...
};

可测试性(Testable)

合理性(Reasonable)

很多人相信使用纯函数最大的好处是引用透明性(referential transparency)。如果一段代码可以替换成它执行所得的结果,而且是在不改变整个程序行为的前提下替换的,那么我们就说这段代码是引用透明的。

并行代码

可以并行运行任意纯函数,因为纯函数根本不需要访问共享的内存,纯函数也不会因为副作用而进入竞争态(race condition)。

柯里化(curry)

柯里化的概念:

只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数。

例如:

function add(x) {
	return function(y) {
		return x + y;
	}
}

高阶函数(higher order function):

参数或者返回值为函数的函数。

函数组合(compose)

例如:

var compose = function(f,g) {
  return function(x) {
    return f(g(x));
  };
};

f 和 g 都是函数,x 是在他们之间通过“管道”传输的值。

@sweeetcc sweeetcc self-assigned this Mar 5, 2017
@sweeetcc sweeetcc added the js label Mar 5, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant