mar*_*lin 10 javascript functional-programming transducer
让我们从定义开始:A transducer
是一个函数,它接受一个reducer
函数并返回一个reducer
函数.
A reducer
是一个二元函数,它接受累加器和值并返回累加器.一个reducer可以用一个reduce
函数执行(注意:所有函数都是curry但是我已经把它和它的定义pipe
以及compose
为了便于阅读 - 你可以在现场演示中看到它们):
const reduce = (reducer, init, data) => {
let result = init;
for (const item of data) {
result = reducer(result, item);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
随着reduce
我们可以实现map
和filter
功能:
const mapReducer = xf => (acc, item) => [...acc, xf(item)];
const map = (xf, arr) => reduce(mapReducer(xf), [], arr);
const filterReducer = predicate => (acc, item) => predicate(item) ?
[...acc, item] :
acc;
const filter = (predicate, arr) => reduce(filterReducer(predicate), [], arr);
Run Code Online (Sandbox Code Playgroud)
我们可以看到,这些函数之间存在一些相似之处map
,filter
并且这两个函数仅适用于数组.另一个缺点是,当我们编写这两个函数时,在每个步骤中都会创建一个临时数组,并将其传递给另一个函数.
const even = n => n % 2 === 0;
const double = n => n * 2;
const doubleEven = pipe(filter(even), map(double));
doubleEven([1,2,3,4,5]);
// first we get [2, 4] from filter
// then final result: [4, 8]
Run Code Online (Sandbox Code Playgroud)
传感器帮助我们解决了这些问题:当我们使用传感器时,没有创建临时阵列,我们可以将我们的函数概括为不仅适用于数组.传感器需要一个传感器通常通过传递给transduce
功能才能工作transduce
函数来执行:
const transduce = (xform, iterator, init, data) =>
reduce(xform(iterator), init, data);
const mapping = (xf, reducer) => (acc, item) => reducer(acc, xf(item));
const filtering = (predicate, reducer) => (acc, item) => predicate(item) ?
reducer(acc, item) :
acc;
const arrReducer = (acc, item) => [...acc, item];
const transformer = compose(filtering(even), mapping(double));
const performantDoubleEven = transduce(transformer, arrReducer, [])
performantDoubleEven([1, 2, 3, 4, 5]); // -> [4, 8] with no temporary arrays created
Run Code Online (Sandbox Code Playgroud)
我们甚至可以定义数组map
和filter
使用transducer
因为它是如此可组合:
const map = (xf, data) => transduce(mapping(xf), arrReducer, [], data);
const filter = (predicate, data) => transduce(filtering(predicate), arrReducer, [], data);
Run Code Online (Sandbox Code Playgroud)
现场版如果你想运行代码 - > https://runkit.com/marzelin/transducers
我的推理有意义吗?
你的理解是正确的,但不完整。
除了您描述的概念之外,传感器还可以执行以下操作:
例如,JavaScript 中的实现需要执行以下操作:
// Ensure reduce preserves early termination
let called = 0;
let updatesCalled = map(a => { called += 1; return a; });
let hasTwo = reduce(compose(take(2), updatesCalled)(append), [1,2,3]).toString();
console.assert(hasTwo === '1,2', hasTwo);
console.assert(called === 2, called);
Run Code Online (Sandbox Code Playgroud)
这里因为调用了take
归约操作而提前退出。
它需要能够(可选)调用不带初始值参数的步骤函数:
// handles lack of initial value
let mapDouble = map(n => n * 2);
console.assert(reduce(mapDouble(sum), [1,2]) === 6);
Run Code Online (Sandbox Code Playgroud)
这里,不带参数的调用sum
返回加性恒等式(零)以作为归约的种子。
为了实现这一点,这里有一个辅助函数:
const addArities = (defaultValue, reducer) => (...args) => {
switch (args.length) {
case 0: return typeof defaultValue === 'function' ? defaultValue() : defaultValue;
case 1: return args[0];
default: return reducer(...args);
}
};
Run Code Online (Sandbox Code Playgroud)
这需要一个初始值(或可以提供初始值的函数)和一个减速器作为种子:
const sum = addArities(0, (a, b) => a + b);
Run Code Online (Sandbox Code Playgroud)
现在sum
具有正确的语义,这也是append
第一个示例中的定义方式。对于有状态转换器,请查看take
(包括辅助函数):
// Denotes early completion
class _Wrapped {
constructor (val) { this[DONE] = val }
};
const isReduced = a => a instanceof _Wrapped;
// ensures reduced for bubbling
const reduced = a => a instanceof _Wrapped ? a : new _Wrapped(a);
const unWrap = a => isReduced(a) ? a[DONE] : a;
const enforceArgumentContract = f => (xform, reducer, accum, input, state) => {
// initialization
if (!exists(input)) return reducer();
// Early termination, bubble
if (isReduced(accum)) return accum;
return f(xform, reducer, accum, input, state);
};
/*
* factory
*
* Helper for creating transducers.
*
* Takes a step process, intial state and returns a function that takes a
* transforming function which returns a transducer takes a reducing function,
* optional collection, optional initial value. If collection is not passed
* returns a modified reducing function, otherwise reduces the collection.
*/
const factory = (process, initState) => xform => (reducer, coll, initValue) => {
let state = {};
state.value = typeof initState === 'function' ? initState() : initState;
let step = enforceArgumentContract(process);
let trans = (accum, input) => step(xform, reducer, accum, input, state);
if (coll === undefined) {
return trans; // return transducer
} else if (typeof coll[Symbol.iterator] === 'function') {
return unWrap(reduce(...[trans, coll, initValue].filter(exists)));
} else {
throw NON_ITER;
}
};
const take = factory((n, reducer, accum, input, state) => {
if (state.value >= n) {
return reduced(accum);
} else {
state.value += 1;
}
return reducer(accum, input);
}, () => 0);
Run Code Online (Sandbox Code Playgroud)
如果你想看看这一切的实际效果,我不久前制作了一个小图书馆。虽然我忽略了 Cognitect 的互操作协议(我只是想了解概念),但我确实尝试根据 Strange Loop 和 Conj 的 Rich Hickey 的演讲尽可能准确地实现语义。
归档时间: |
|
查看次数: |
196 次 |
最近记录: |