それマグで!

知識はカップより、マグでゆっくり頂きます。 takuya_1stのブログ

習慣に早くから配慮した者は、 おそらく人生の実りも大きい。

なんにつかうの? filter(), map(), reduce()

正直何に使うんだろう?と一瞬わからなかった。こいつら。filter, map, reduce。理解すると便利なので覚えよう。

  • 配列のそれぞれに対して、Callbackしてくれる関数群。
  • PHPだとarray_walk()。
  • 機能は__iter__()とGenerator使えば実現できる
def f(x): return x%2 == 0 #偶数かどうか調べる

print filter( f, range(1,10) )

# [ 2,4,6,8,]

JavaScript (prototype.js) ならこうなる

<script type="text/javascript" src="prototype.js" ></script>
<script type="text/javascript">

    var hoge = $R( 1,10, true );
    hoge = hoge.findAll( function(v){ return v%2==0; } );
    document.write(hoge);

    //hoge = 2,4,6,8

</script>


覚え方、配列にフィルタを掛ける。だから filter() ここは試験に出ますぉ


ちなみにPHPならこんなことになる

<?php

$hoge = range(1,9);
$hoge = array_filter( $hoge, create_function( '&$v, $i', 'return !($v&1);' ) );

var_dump($hoge);

$hoge = array_filter() が特徴的かな。

PHPは結果を代入することが多い、代入忘れがエラーの元に。ちなみにfilter()も結果を変数に代入が必要だよ。JavaScriptは代入不要。これは、Arrayの親クラスEnumerableが代入をやってくれてるから。

map()

prototype.jsだと、Enumerable.each() に相当する。Iteratorだとわかれば後は簡単。

#pow
seq = range( 1,10 );
seq = map( lambda x : x*x, seq )
print seq

reduce()

これは、PythonのドキュメントよりPHPのarray_reduce()のdocの説明がわかりやすい。

array_reduce() applies iteratively the function function to the elements of the array input, so as to reduce the array to a single value. If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty. If the array is empty and initial is not passed, array_reduce() returns NULL.


array_reduce() は、配列 input の各要素に function 関数を繰り返し適用し、 配列を一つの値に減らします.オプション intial が利用可能な場合、処理の最初で使用されたり、 配列が空の場合の最終結果として使用されます。 配列が空で initial が渡されなかった場合は、 array_reduce() は NULL を返します。


phpマニュアルより

使用例。

#階乗
seq = range( 1,10 );
print map( lambda x,y : x*y, seq )
#[1, 4, 9, 16, 25, 36, 49, 64, 81]