0
点赞
收藏
分享

微信扫一扫

Java分布式架构设计与开发实战2022全新版

Java分布式架构设计与开发实战2022全新版

download:http://www.51xuebc.com/thread-448-1-1.html

万物皆可柯里化的 Ramda.js我们前段时间写过好几篇关于 RxJS 的文章,RxJS api 操作符了解起来的确比拟复杂,RxJS 是函数式编程中的 lodash 库,它消弭了“时序”而带来的搅扰,它中心思想是:函数式 + 响应式。本篇, 要讲的不是 RxJS,而是另外一个函数式编程库 Ramda.js ,它同样也能够与 loadsh 比照了解,不过它的设计思绪又不同了,它最大的特性是:一切函数都能够柯里化传参!以此来践行函数式编程思想。

往下看,后面我们就能明白:Ramda 一切 Api 都能柯里化的意义所在。Function first,Data last在 lodash 中,我们是这样写的,var square = n => n * n;_.map([4, 8], square)

参数在前,执行函数在后。而在 Ramda 中,强调:函数在前,参数在后。这样做有什么益处呢?就是为了更好完成:柯里化。柯里化只需求参数一个一个的在后var R = require('ramda');R.map(square, [4, 8])

// 同等于

var R = require('ramda');R.map(square)([4, 8])

再举个栗子:var R = require('ramda');

const odd = x => x%2 === 1const data = [3, 5, 6];

R.filter(odd, data); // [3, 5]

// 同等于R.filter(odd)(data); // [3, 5]

// 也能够延迟调用const filter1 = R.filter(odd);// filter1 等候参数的传入// 后续再传入 dataconst filter2 = filter1(data)

假如不借用 Ramda.js , 需求自行完成柯里化,就会显得费事:const _curry = f => a => b => f(a, b)const odd = x => x%2 === 1

const _filter = _curry( (fn, arr) => arr.filter(fn) );_filter(odd)([3,5,6]) // [3, 5]

Ramda 十分强调:R.api(fn, data) 这样的范式;API来看看 Ramda 有哪些神奇的、好用的、常用的 API~

map

map 让每个成员依次执行经过某个函数;const double = x => x * 2;

R.map(double, [1, 2, 3]); //=> [2, 4, 6]

R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6}


filter

用于过滤;const isEven = n => n % 2 === 0;

R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4]R.filter(isEven, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4}


add

求和;R.add(2, 3);       //=>  5R.add(7)(10);      //=> 17


multiply

求积;R.multiply(2)(5)  // 10


compose

函数组合,从右到左;R.compose(Math.abs, R.add(1), R.multiply(2))(-4)

// |-4*2 + 1|,等于 7


pipe

函数组合,从左到右;var negative = x => -1 * x;var increaseOne = x => x + 1;

var f = R.pipe(Math.pow, negative, increaseOne)(3,4);

// -(3^4) + 1 ,等于 -80


curry

将多个参数转换为单个参数const addFourNumbers = (a, b, c, d) => a + b + c + d;

const curriedAddFourNumbers = R.curry(addFourNumbers);

curriedAddFourNumbers(1, 2)(3)(4)

Ramda 还有其它丰厚的 api,也能够分离 compose/pipe 自定义特定功用函数,用这些办法来简化程序,让代码变成函数式作风;

举报

相关推荐

0 条评论