In the previous article we mentioned the concept of pure functions. The so-called pure functions are, For the same input, you will always get the same output without any observable side effects. , and does not rely on the status of the external environment (I copied it lazily).
But in actual programming, especially in the field of front-end programming, the condition of "not relying on the external environment" is simply impossible. We are always inevitably exposed to states such as DOM and AJAX. Something that changes all the time. So we need to use more powerful technology to do the dirty work.
If you are familiar with jQuery, you should still remember that the object returned by $(...) is not a native DOM object, but A kind of encapsulation of native objects:
var foo = $('#foo'); foo == document.getElementById('foo'); //=> false foo[0] == document.getElementById('foo'); //=> true
This is a "container" in a sense (but it is not functional).
We will see in the next class that containers provide an extremely powerful coating for ordinary variables, objects, and functions in functional programming, giving them some amazing features, just like Tony Stark's The steel coat, Dva's mecha, is the same as Asuka's Unit 2.
Let’s write the simplest container:
var Container = function(x) { this.__value = x; } Container.of = x => new Container(x); //试试看 Container.of(1); //=> Container(1) Container.of('abcd'); //=> Container('abcd')
After we call Container.of to put things into the container, due to the obstruction of this layer of shell, ordinary functions It no longer works for them, so we need to add an interface to allow external functions to also affect the values in the container:
Container.prototype.map = function(f){ return Container.of(f(this.__value)) }
We can use it like this It:
Container.of(3) .map(x => x + 1) //=> Container(4) .map(x => 'Result is ' + x); //=> Container('Result is 4')
chain call", which is also our first Functor.
Functor is a container type that implements map and obeys some specific rules.
In other words, if we want to apply a normal function to a value wrapped in a container, then we first need to define a data type calledFunctor. In this data type You need to define how to use map to apply this ordinary function.
Put things into a container and leave only one interfacemap for functions outside the container. What are the benefits of doing this?
Essentially,Functor is an abstraction for function calls. We give the container the ability to call functions by itself. When map a function, we let the container run the function by itself, so that the container can freely choose when, where and how to operate the function, so that it has lazy evaluation, error handling, asynchronous calling, etc. Waiting for very awesome features.
For example, we now add a feature to check for null values to themap function. This new container we call Maybe (the prototype comes from Haskell) :
var Maybe = function(x) { this.__value = x; } Maybe.of = function(x) { return new Maybe(x); } Maybe.prototype.map = function(f) { return this.isNothing() ? Maybe.of(null) : Maybe.of(f(this.__value)); } Maybe.prototype.isNothing = function() { return (this.__value === null || this.__value === undefined); } //试试看 import _ from 'lodash'; var add = _.curry(_.add); Maybe.of({name: "Stark"}) .map(_.prop("age")) .map(add(10)); //=> Maybe(null) Maybe.of({name: "Stark", age: 21}) .map(_.prop("age")) .map(add(10)); //=> Maybe(31)
import _ from 'lodash'; var compose = _.flowRight; var add = _.curry(_.add); // 创造一个柯里化的 map var map = _.curry((f, functor) => functor.map(f)); var doEverything = map(compose(add(10), _.property("age"))); var functor = Maybe.of({name: "Stark", age: 21}); doEverything(functor); //=> Maybe(31)
try{ doSomething(); }catch(e){ // 错误处理 }
doSomething() .then(async1) .then(async2) .catch(e => console.log(e));
// 这里是一样的=。= var Left = function(x) { this.__value = x; } var Right = function(x) { this.__value = x; } // 这里也是一样的=。= Left.of = function(x) { return new Left(x); } Right.of = function(x) { return new Right(x); } // 这里不同!!! Left.prototype.map = function(f) { return this; } Right.prototype.map = function(f) { return Right.of(f(this.__value)); }
Right.of("Hello").map(str => str + " World!"); // Right("Hello World!") Left.of("Hello").map(str => str + " World!"); // Left("Hello")
Left and Right is the implementation of the map method, the behavior of Right.map is different from ours The same as the map function mentioned before. But Left.map is very different: It doesn't do anything with the container, it just takes the container in and throws it out. This feature means that Left can be used to deliver an error message.
var getAge = user => user.age ? Right.of(user.age) : Left.of("ERROR!"); //试试 getAge({name: 'stark', age: '21'}).map(age => 'Age is ' + age); //=> Right('Age is 21') getAge({name: 'stark'}).map(age => 'Age is ' + age); //=> Left('ERROR!')
Left can make any link in the call chain The error is immediately returned to the end of the call chain, which brings us great convenience in error handling. We no longer need to go through layers of try/catch.
Left 和 Right 是 Either 类的两个子类,事实上 Either 并不只是用来做错误处理的,它表示了逻辑或,范畴学里的 coproduct。但这些超出了我们的讨论范围。
下面我们的程序要走出象牙塔,去接触外面“肮脏”的世界了,在这个世界里,很多事情都是有副作用的或者依赖于外部环境的,比如下面这样:
function readLocalStorage(){ return window.localStorage; }
这个函数显然不是纯函数,因为它强依赖外部的 window.localStorage 这个对象,它的返回值会随着环境的变化而变化。为了让它“纯”起来,我们可以把它包裹在一个函数内部,延迟执行它:
function readLocalStorage(){ return function(){ return window.localStorage; } }
这样 readLocalStorage 就变成了一个真正的纯函数! OvO为机智的程序员鼓掌!
额……好吧……好像确实没什么卵用……我们只是(像大多数拖延症晚期患者那样)把讨厌做的事情暂时搁置了而已。为了能彻底解决这些讨厌的事情,我们需要一个叫 IO 的新的 Functor:
import _ from 'lodash'; var compose = _.flowRight; var IO = function(f) { this.__value = f; } IO.of = x => new IO(_ => x); IO.prototype.map = function(f) { return new IO(compose(f, this.__value)) };
IO 跟前面那几个 Functor 不同的地方在于,它的 __value 是一个函数。它把不纯的操作(比如 IO、网络请求、DOM)包裹到一个函数内,从而延迟这个操作的执行。所以我们认为,IO 包含的是被包裹的操作的返回值。
var io_document = new IO(_ => window.document); io_document.map(function(doc){ return doc.title }); //=> IO(document.title)
注意我们这里虽然感觉上返回了一个实际的值 IO(document.title),但事实上只是一个对象:{ __value: [Function] },它并没有执行,而是简单地把我们想要的操作存了起来,只有当我们在真的需要这个值得时候,IO 才会真的开始求值,这个特性我们称之为『惰性求值』。(培提尔其乌斯:“这是怠惰啊!”)
是的,我们依然需要某种方法让 IO 开始求值,并且把它返回给我们。它可能因为 map 的调用链积累了很多很多不纯的操作,一旦开始求值,就可能会把本来很干净的程序给“弄脏”。但是去直接执行这些“脏”操作不同,我们把这些不纯的操作带来的复杂性和不可维护性推到了 IO 的调用者身上(嗯就是这么不负责任)。
下面我们来做稍微复杂点的事情,编写一个函数,从当前 url 中解析出对应的参数。
import _ from 'lodash'; // 先来几个基础函数: // 字符串 var split = _.curry((char, str) => str.split(char)); // 数组 var first = arr => arr[0]; var last = arr => arr[arr.length - 1]; var filter = _.curry((f, arr) => arr.filter(f)); //注意这里的 x 既可以是数组,也可以是 functor var map = _.curry((f, x) => x.map(f)); // 判断 var eq = _.curry((x, y) => x == y); // 结合 var compose = _.flowRight; var toPairs = compose(map(split('=')), split('&')); // toPairs('a=1&b=2') //=> [['a', '1'], ['b', '2']] var params = compose(toPairs, last, split('?')); // params('http://xxx.com?a=1&b=2') //=> [['a', '1'], ['b', '2']] // 这里会有些难懂=。= 慢慢看 // 1.首先,getParam是一个接受IO(url),返回一个新的接受 key 的函数; // 2.我们先对 url 调用 params 函数,得到类似[['a', '1'], ['b', '2']] // 这样的数组; // 3.然后调用 filter(compose(eq(key), first)),这是一个过滤器,过滤的 // 条件是 compose(eq(key), first) 为真,它的意思就是只留下首项为 key // 的数组; // 4.最后调用 Maybe.of,把它包装起来。 // 5.这一系列的调用是针对 IO 的,所以我们用 map 把这些调用封装起来。 var getParam = url => key => map(compose(Maybe.of, filter(compose(eq(key), first)), params))(url); // 创建充满了洪荒之力的 IO!!! var url = new IO(_ => window.location.href); // 最终的调用函数!!! var findParam = getParam(url); // 上面的代码都是很干净的纯函数,下面我们来对它求值,求值的过程是非纯的。 // 假设现在的 url 是 //m.sbmmt.com/ // 调用 __value() 来运行它! findParam("a").__value(); //=> Maybe(['a', '1'])
如果你还能坚持看到这里的话,不管看没看懂,已经是勇士了。在这篇文章里,我们先后提到了 Maybe、Either、IO 这三种强大的 Functor,在链式调用、惰性求值、错误捕获、输入输出中都发挥着巨大的作用。事实上 Functor 远不止这三种,但由于篇幅的问题就不再继续介绍了(哼才不告诉你其实是因为我还没看懂其它 Functor 的原理)
但依然有问题困扰着我们:
1. 如何处理嵌套的 Functor 呢?(比如 Maybe(IO(42)))
2. 如何处理一个由非纯的或者异步的操作序列呢?
在这个充满了容器和 Functor 的世界里,我们手上的工具还不够多,函数式编程的学习还远远没有结束,在下一篇文章里会讲到 Monad 这个神奇的东西(然而我也不知道啥时候写下一篇,估计等到实习考核后吧OvO)。
以上就是JavaScript函数式编程(二)的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!