链接映射减少过滤器时如何减少迭代次数?

时间:2018-03-11 15:14:49

标签: javascript functional-programming monads

我一直在阅读有关mapreducefilter的内容,因为它们在反应和FP中的使用量有多大。如果我们写下这样的话:

let myArr = [1,2,3,4,5,6,7,8,9]
let sumOfDoubleOfOddNumbers = myArr.filter(num => num % 2)
                                   .map(num => num * 2)
                                   .reduce((acc, currVal) => acc + currVal, 0);

运行3个不同的循环。

我也读过Java 8流,并且知道他们使用所谓的monad,即首先存储计算。它们仅在一次迭代中执行一次。例如,

Stream.of("d2", "a2", "b1", "b3", "c")
    .map(s -> {
        System.out.println("map: " + s);
        return s.toUpperCase();
    })
    .filter(s -> {
        System.out.println("filter: " + s);
        return s.startsWith("A");
    })
    .forEach(s -> System.out.println("forEach: " + s));

// map:     d2
// filter:  D2
// map:     a2
// filter:  A2
// forEach: A2
// map:     b1
// filter:  B1
// map:     b3
// filter:  B3
// map:     c
// filter:  C

PS:Java代码取自:http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/

还有许多其他语言使用相同的方法。有没有办法在JS中以同样的方式做到这一点?

4 个答案:

答案 0 :(得分:2)

这是Java代码的精确克隆。与Bergi的解决方案不同,无需修改全局原型。



class Stream {
    constructor(iter) {
        this.iter = iter;
    }

    * [Symbol.iterator]() {
        yield* this.iter;
    }

    static of(...args) {
        return new this(function* () {
            yield* args
        }());
    }

    _chain(next) {
        return new this.constructor(next.call(this));
    }

    map(fn) {
        return this._chain(function* () {
            for (let a of this)
                yield fn(a);
        });
    }

    filter(fn) {
        return this._chain(function* () {
            for (let a of this)
                if (fn(a))
                    yield (a);
        });
    }

    forEach(fn) {
        for (let a of this)
            fn(a)
    }
}


Stream.of("d2", "a2", "b1", "b3", "c")
    .map(s => {
        console.log("map: " + s);
        return s.toUpperCase();
    })
    .filter(s => {
        console.log("filter: " + s);
        return s.startsWith("A");
    })
    .forEach(s => console.log('forEach', s));




实际上,链接功能可以与特定迭代器分离,以提供通用框架:

// polyfill, remove me later on
Array.prototype.values = Array.prototype.values || function* () { yield* this };

class Iter {
    constructor(iter)     { this.iter = iter }
    * [Symbol.iterator]() { yield* this.iter }
    static of(...args)    { return this.from(args) }
    static from(args)     { return new this(args.values()) }
    _(gen)                { return new this.constructor(gen.call(this)) }
}

现在,您可以将任意生成器(包括预定义生成器和临时生成器)放入其中,例如:

let map = fn => function* () {
    for (let a of this)
        yield fn(a);
};

let filter = fn => function* () {
    for (let a of this)
        if (fn(a))
            yield (a);
};

it = Iter.of("d2", "a2", "b1", "b3", "c", "a000")
    ._(map(s => s.toUpperCase()))
    ._(filter(s => s.startsWith("A")))
    ._(function*() {
        for (let x of [...this].sort())
            yield x;
    });

console.log([...it])

答案 1 :(得分:1)

你可以使用管道实现这一点,如果这太复杂了我不知道,但是通过使用管道你可以在管道上调用Array.reduce并且它在每次迭代时执行相同的行为。

const stream = ["d2", "a2", "b1", "b3", "c"];

const _pipe = (a, b) => (arg) => b(a(arg));
const pipe = (...ops) => ops.reduce(_pipe);

const _map = (value) => (console.log(`map: ${value}`), value.toUpperCase());
const _filter = (value) => (console.log(`filter: ${value}`), 
value.startsWith("A") ? value : undefined);
const _forEach = (value) => value ? (console.log(`forEach: ${value}`), value) : undefined;

const mapFilterEach = pipe(_map,_filter,_forEach);

const result = stream.reduce((sum, element) => {
    const value = mapFilterEach(element);
    if(value) sum.push(value);
    return sum;
}, []);

我从here

获取了管道功能

以下是管道缩小的填充物,如果您想将其用于更动态的目的,则为示例

Array.prototype.pipeReduce = function(...pipes){
    const _pipe = (a, b) => (arg) => b(a(arg));
    const pipe = (...ops) => ops.reduce(_pipe);
    const reducePipes = pipe(...pipes);
    return this.reduce((sum, element) => {
        const value = reducePipes(element);
        if(value) sum.push(value);
        return sum;
    }, []);
};

const stream = ["d2", "a2", "b1", "b3", "c"];

const reduced = stream.pipeReduce((mapValue) => {
    console.log(`map: ${mapValue}`);
    return mapValue.toUpperCase();
}, (filterValue) => {
    console.log(`filter: ${filterValue}`);
    return filterValue.startsWith("A") ? filterValue : undefined;
}, (forEachValue) => {
    if(forEachValue){
        console.log(`forEach: ${forEachValue}`);
        return forEachValue;
    }
    return undefined;
});

console.log(reduced); //["A2"]

答案 2 :(得分:1)

  

所谓的monad,即首先存储计算

嗯,不,那不是Monad的含义。

  

有没有办法在JS中以同样的方式做到这一点?

是的,您可以使用迭代器。检查this实施或that one(以及monad方法,here)。

const myArr = [1,2,3,4,5,6,7,8,9];
const sumOfDoubleOfOddNumbers = myArr.values() // get iterator
                                .filter(num => num % 2)
                                .map(num => num * 2)
                                .reduce((acc, currVal) => acc + currVal, 0);
console.log(sumOfDoubleOfOddNumbers);

["d2", "a2", "b1", "b3", "c"].values()
.map(s => {
    console.log("map: " + s);
    return s.toUpperCase();
})
.filter(s => {
    console.log("filter: " + s);
    return s.startsWith("A");
})
.forEach(s => console.log("forEach: " + s));

var IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
IteratorPrototype.map = function*(f) {
    for (var x of this)
        yield f(x);
};
IteratorPrototype.filter = function*(p) {
    for (var x of this)
        if (p(x))
            yield x;
};
IteratorPrototype.reduce = function(f, acc) {
    for (var x of this)
        acc = f(acc, x);
    return acc;
};
IteratorPrototype.forEach = function(f) {
    for (var x of this)
        f(x);
};
Array.prototype.values = Array.prototype[Symbol.iterator];

const myArr = [1,2,3,4,5,6,7,8,9];
const sumOfDoubleOfOddNumbers = myArr.values() // get iterator
                                .filter(num => num % 2)
                                .map(num => num * 2)
                                .reduce((acc, currVal) => acc + currVal, 0);
console.log({sumOfDoubleOfOddNumbers});

["d2", "a2", "b1", "b3", "c"].values()
.map(s => {
    console.log("map: " + s);
    return s.toUpperCase();
})
.filter(s => {
    console.log("filter: " + s);
    return s.startsWith("A");
})
.forEach(s => console.log("forEach: " + s));

在生产代码中,您可能应该使用静态函数,而不是在内置迭代器原型上放置自定义方法。

答案 3 :(得分:1)

Array.prototype.mapArray.prototype.filter会创建前一个数组。 Array.prototype.reduce对累加器和数组中的每个元素(从左到右)应用函数以将其减少为单个值。

因此,它们都不允许进行懒惰的评估。

您可以通过将多个循环减少为一个来实现懒惰:



const array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const result = array.reduce((acc, x) => x % 2 ? acc += x * 2 : acc, 0);
console.log(result);




另一种方法是在自定义对象中自己处理延迟评估,如下所示。下一个代码段是重新定义filtermap

的示例



const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// convert to a lazy structure...
const results = toLazy(array)
  .filter(x => {
    console.log('filter', x);
    return x % 2 !== 0;
  })
  .map(x => {
    console.log('map', x);
    return x * 2;
  });

// check logs for `filter` and `map` callbacks
console.log(results.run()); // -> [2, 6, 10, 14, 18]

function toLazy(array) {
  const lazy = {};
  let callbacks = [];

  function addCallback(type, callback) {
    callbacks.push({ type, callback });
    return lazy;
  }

  lazy.filter = addCallback.bind(null, 'filter');
  lazy.map = addCallback.bind(null, 'map');

  lazy.run = function () {
    const results = [];

    for (var i = 0; i < array.length; i += 1) {
      const item = array[i];
      for (var { callback, type } of callbacks) {
        if (type === 'filter') {
          if (!callback(item, i)) {
            break;
          }
        } else if (type === 'map') {
          results.push(callback(item, i));
        }
      }
    }

    return results;
  };

  return lazy;
}
&#13;
&#13;
&#13;

但是,您可以使用lazy.js检查iterators等库,这些库提供了一个懒惰的引擎。