[Transducer] Step by Step to build a simple transducer
Transducers are composable algorithmic transformations. They are independent from the context of their input and output sources and specify only the essence of the transformation in terms of an individual element. Because transducers are decoupled from input or output sources, they can be used in many different processes - collections, streams, channels, observables, etc. Transducers compose directly, without awareness of input or creation of intermediate aggregates.
OK, short in description... let's see why we need it
- Normal Javascript `map`,`filter` create inter variable and loop though array everytime we call `map` or `filter` function, `transducer` can loop thought the array only ONCE and apply all the transofrmations necessary.
const data = [,,];
const inc = x => x + ;
const double = x => * x;
const lessThanThree = x => x < ;
////////////////////
/**
* Problem: We loop over array 3 times! We want to loop over only once
* in order to improve the profermance.
*/
const res1 = data
.filter(lessThanThree)
.map(double)
.map(inc) console.log(res1) // [3,5]
2. We don't want to introduce any mutation or impure function such as `forEach` does, transducer are mutation free.
/**
* Problem: it is not pure function and we do mutation. But it is faster
* than we do .filter.map.map style, because it only loop the array once.
*/
let res2 = [];
data.forEach((x) => {
let item;
if (lessThanThree(x)) {
item = inc(double(x))
res2.push(item);
}
})
console.log(res2) // [3,5]
3. We want to style functional style to keep the code more readable, in the meanwhile improve the proferemance:
/**
* Good: We avoid the mutation and can be write as pure function and it only loop once!
* Problem: But we lose our function composion style! We still want .filter.map.map styling.
* Meanwhile it should be profermance wise.
*/
const res3 = data.reduce((acc, curr) => {
if (lessThanThree(curr)) {
acc.push(inc(double(curr)));
}
return acc;
}, []);
console.log(res3); // [3,5]
OK, until now, we have some idea, what kind of code we want. Basiclly it should be composable and efficient.
The question is how to make composable code?
As we might know about, in OOP; if we want to chain multi function calls, from each function, we need to return `this`:
Class Bot {
...
sayName() {
console.log(this,name)
return this;
}
sayHello() {
console.log("Hello")
return this;
}
}
const b = new Bot('Petter')
b.sayName().sayHello()
For Array, the reason we can chain calls together is because each call return Array type. The same as String, number...
The key is we need to keep the input and output as the same type!
Therefore for function, we need to keep input function and output function have the same function signature!
//data.reduce(reducer, seed), reducer is something we can compose!
//Because reducer :: (acc, curr) => acc
//For every reducer functions' signature are the same.
//If the function sinature are the same, then we can compose function together!
const _mapReducer = (xf, array) =>
array.reduce((acc, curr) => {
acc.push(xf(curr))
return acc;
}, []);
const _filterReducer = (xf, array) =>
array.reduce((acc, curr) => {
if (xf(curr)) acc.push(curr);
return acc;
}, []);
// To make fns easy to compose, we extract 'array' data & init value
const mapReducer = (xf) => ((acc, curr) => {
acc.push(xf(curr))
return acc;
});
const filterReducer = pred => ((acc, curr) => {
if (pred(curr)) acc.push(curr);
return acc;
});
// now mapReducer and filterReducer both have the same function signature.
console.log(data.reduce(mapReducer(double), [])); // [2,4,6]
console.log(data.reduce(mapReducer(inc), [])); // [2,3,4]
console.log(data.reduce(filterReducer(lessThanThree), [])); // [1,2]
// In order to compose reudcers together we need to make mapReducer and filterReducer as high order functions to take reducer as arguement
// Take a reducer as input and return a reducer signature as output is the key to do composion!
const map = xf => reducer => ((acc, curr) => {
acc = reducer(acc, xf(curr))
return acc;
});
const filter = pred => reducer => ((acc, curr)=> {
if (pred(curr)) acc = reducer(acc, curr)
return acc;
})
// For mapReducer and filterReducer, we both do acc.push()
// therefore we can extrat this as base reducer
const pushReducer = (acc, value) => {
acc.push(value);
return acc;
};
const doulbeLessThanThree = compose(
map(inc),
map(double),
filter(lessThanThree)
)
const res5 = data.reduce(doulbeLessThanThree(pushReducer), []);
console.log(res5); // [3,5]
Define our transducer!
/**
* transducer :: ((a -> b -> a), (a -> b -> a), [a], [a]) -> [a]
* @param {*} xf: base reducer
* @param {*} reducer: the composion redcuer signature
* @param {*} seed : init value
* @param {*} collection : data
*/
const transducer = (xf, reducer, seed, collection) => {
return collection.reduce(reducer(xf), seed);
}
const res6 = transducer(pushReducer, doulbeLessThanThree, [], data);
console.log(res6); // [3,5]
[Transducer] Step by Step to build a simple transducer的更多相关文章
- Build step 'Execute shell' marked build as failure解决
今天jenkins构建时运行脚本报错如下: Build step 'Execute shell' marked build as failure 脚本没问题后来看了下原因是磁盘空间不足导致报错,清除下 ...
- Jenkins Build step 'Execute shell' marked build as failure
问题出现: Jenkins一直都构建成功,今天突然报错:Jenkins Build step 'Execute shell' marked build as failure 问题原因: By defa ...
- [转]Bootstrap 3.0.0 with ASP.NET Web Forms – Step by Step – Without NuGet Package
本文转自:http://www.mytecbits.com/microsoft/dot-net/bootstrap-3-0-0-with-asp-net-web-forms In my earlier ...
- Tomcat Clustering - A Step By Step Guide --转载
Tomcat Clustering - A Step By Step Guide Apache Tomcat is a great performer on its own, but if you'r ...
- Code Understanding Step by Step - We Need a Task
Code understanding is a task we are always doing, though we are not even aware that we're doing it ...
- 课程四(Convolutional Neural Networks),第一周(Foundations of Convolutional Neural Networks) —— 2.Programming assignments:Convolutional Model: step by step
Convolutional Neural Networks: Step by Step Welcome to Course 4's first assignment! In this assignme ...
- Convolutional Neural Networks: Step by Step
Andrew Ng deeplearning courese-4:Convolutional Neural Network Convolutional Neural Networks: Step by ...
- Sequence Models Week 1 Building a recurrent neural network - step by step
Building your Recurrent Neural Network - Step by Step Welcome to Course 5's first assignment! In thi ...
- Step by step Process of creating APD
Step by step Process of creating APD: Business Scenario: Here we are going to create an APD on top o ...
随机推荐
- Python并发编程-事件,红绿灯控制
事件用来控制多个进程同时执行或者阻塞 set和clear 分别用来修改一个事件的状态,True或者False is_set 用来查看一个事件的状态 wait 是依据事件的状态来决定自己是否在wait处 ...
- Python类总结-封装(私有属性,方法)
封装基础 广义上面向对象的封装:代码的保护,面向对象的思想本身就是一种封装 只让自己的对象能调用自己类中的方法 狭义上的封装-面向对象三大特性之一(私有变量,用公有的方法封装私有属性,方法叫封装) 把 ...
- The dd command of linux
The dd command stands for "data duplicator" and used for copying and converting data. It i ...
- chomd 1+2+4
2,把目录 /tmp/sco修改为可写可读可执行 chmod 777 /tmp/sco 要修改某目录下所有的文件夹属性为可写可读可执行 chmod 777 * 把文件夹名称用*来代替就可以了 要修改/ ...
- 【LeetCode】shell
195. Tenth Line 输出file.txt中的第十行 答案: # Read from the file file.txt and output the tenth line to stdou ...
- RxJava 机制
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha rxjava 是 以 响应式 编程思想 编程的 java类库
- ARC 058
所以为啥要写来着........... 链接 T1 直接枚举大于等于$n$的所有数,暴力分解判断即可 复杂度$O(10n \log n)$ #include <cstdio> #inclu ...
- 埃及分数 a* 搜索 知识点mark
题意 在古埃及,人们使用单位分数的和(即1/a,a是自然数)表示一切有理 数. 例如,2/3=1/2+1/6,但不允许2/3=1/3+1/3,因为在加数中不允许有相同的. 对于一个分数a/b,表示方法 ...
- NYOJ 298 点的变换 矩阵乘法
http://acm.nyist.net/JudgeOnline/problem.php?pid=298 最好还是自己手推一下矩阵式子..不算太难..但是有一些小知识.... 首先当然是矩阵的细节.. ...
- php上传中文文件文件名乱码问题
php上传文件是最最基础的一个技术点,但是深入进去也有不少问题需要解决,这不,上传中文文件后,文件名变成了乱码. 下面是问题代码,很简单: 1.问题代码 html部分: <html> &l ...