0

Say we have

var i = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

and want to reduce() it like

var plus = function(a, b)
{
  return a + b;
};

var s = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  .reduce(plus);

console.log(s);

Now, I want to compose reduce() function itself from map() function.

How would you do that? What is the smartest way?

Edit:

In the comments and answers, many have claimed fold/reduce can compose map, in shallow level, that can be true, however, in category theory, fundamentally reduce/fold is generalized to Catamorphism and it's all about functors (map), and it's called F-algebra.

https://en.wikipedia.org/wiki/Catamorphism

https://en.wikipedia.org/wiki/F-algebra

4

2 に答える 2

1

reduce を使用して map 関数を構築しようとしている場合は、次のようにできます (ここで提供する例は、組み込み関数を使用し、配列に対してのみ機能します!):

var numbers = [1,2,3,4,5];
var map = function(arr, callback) {
  return arr.reduce(function(start, value) {
    start.push(callback(value));
    return start;
  }, []);
};

var newArray = map(numbers, function(value) {
  return value * 3;
});
console.log(newArray); // prints [3,6,9,12,15]

これは、numbers 配列の各値を繰り返し処理し、ループしている現在の値を使用してコールバック関数を呼び出し (実行)、reduce の最後に返される空の配列にこの値をプッシュします。つまり、コールバック関数の結果を新しい配列にマップします!

そうは言っても、関数型プログラミングに興味がある場合は、underscorejs の注釈付きソース コードをチェックすることをお勧めします。

于 2015-01-07T02:52:10.460 に答える
1

map配列内のすべての値に対して 1 つの値を返すため、結果は入力配列と同じ大きさの配列になります。そこから 1 つの値を取得する唯一の方法は、値を 1 つだけ送信することです。

[[1,2,3,4,54]].map(
    function(d){
        sum = d.reduce(function(s,d){
                     return s+d
                 });
        console.log(sum)
    }
);
于 2015-01-07T07:15:21.863 に答える