æ±ç¨çãªaccumulateãæ¸ããªãè¨èªä½¿ãã§è¨±ãããã®ã¯å°å¦çã¾ã§ã
æ¬æ¥ã楽ãã楽ããSICPèªæ¸ä¼ã«è¡ã£ã¦ãã¾ããããé«éæç¶ãã使ã£ãsumâproductâaccumulateâfiltered-accumulateã®æµãã¯ä½ãã«ç¾å³ããã¦ããããã¤ã¾ã¿ã«æ¥æ¬é ä¸åãããã¯ç©ºãããããã§ã
ãã®ãDon't Repeat Yourselfãä½ç¾ãã話ã®æµãã¯å®è½çã«ç¾ããããã§ãã
ããã§ããã£ã±ãæ±ç¨çãªaccumulateãæ¸ããªããããªããã°ã©ãã³ã°è¨èª(ä¾ãã°Java)ã¯ãscript kiddyã使ãã«ã¯ããã¨ãã¦ã大人ã使ãè¨èªãããªãã ããã¨æãããã§ãã
C++ã®ãããªå¤æ è¨èªã ã£ã¦æ¸ããã®ã«ããã¨ããªãã¨ãããæãããã§ãããJavaã£ã¦ããã¦åæ¨è«ã§ãã¤ãã¦ãããªãã¨ä½¿ãç©ã«ãªããªããï¼
C++çaccumulateã®å®è¡ã¯ãã¡ãã§ã
http://codepad.org/A23rW5pA
#include<iostream> #include<list> #include<string> using namespace std; template<typename T> T add(const T& lhs, const T& rhs){ return lhs + rhs; } template<typename T> T mul(const T& lhs, const T& rhs){ return lhs * rhs; } template<typename T> T accumulate(T (*comb)(const T&, const T&), const T& initial, list<T>& ls){ T ret(initial); typedef typename list<T>::iterator Iterator; for( Iterator i=ls.begin(); i!=ls.end(); i++ ){ ret = comb(ret, *i); } return ret; } int main(){ list<int> ls; for( int i=0; i<10; i++){ ls.push_back(i+1); } cout << accumulate(add, 0, ls) << endl; cout << accumulate(mul, 1, ls) << endl; list<string> ls2; ls2.push_back("a"); ls2.push_back("b"); ls2.push_back("c"); ls2.push_back("d"); ls2.push_back("e"); string empty(""); cout << accumulate(add, empty, ls2) << endl; return 0; }