Drkcore

16 08 2007 perl SICP Tweet

perlでaccumulate

最近朝起きてSICPを読んでる。で、SICPの2章も中盤を越えて、accumulateを使って行列の演算を定義した。

ふむーこれはpythonでやってみたいなと思ってたら、ちょうどタイミングよくpythonでやってる人がいた。

ので、perlで。

sub accumulate{
 my ($op, $init, $list) = @_;
 @$list == () ? return $init :
   return $op->(shift(@$list),accumulate($op,$init,$list));
}

my $test_func = sub {return $_[0]+$_[1];};
my $test_list = [1,2,3,4,5];

print accumulate($test_func, 0, $test_list);

で、SICPみたいに、たたみこむだけじゃなくてリストを戻したい。

my $cons = sub {return [@{$_[1]},$_[0]];};
XXX accumulate($cons, [], [1,2,3,4,5]);

List::Utilでも同じことできるみたいですが。自分で書いてみたかったということで。

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021