Skip to content

Latest commit

 

History

History
68 lines (50 loc) · 1.71 KB

File metadata and controls

68 lines (50 loc) · 1.71 KB

Higher Order Functions

” … higher-order functions can take functions as argument or return them as result… ”

” … Each programming language supporting programming in the functional style supports at least the three functions map, filter, and fold. map applies a function to each element of its list. filter removes all elements of a list not satisfying a condition. fold is the most powerful of the three ones. fold successively applies a binary operation to pairs of the list and therefore reduces the list to a value … ”

map ------> std::transform filter —> std::remove_if fold -----> std::accumulate

Source code and text Quoted from: http://www.modernescpp.com/index.php/higher-order-functions

#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
#include <string>
#include <numeric>

using namespace std;

int main()
{
	std::vector<string> str {"programming", "in", "a", "functional", "style"};
	 	    
	//map
	std::vector<int> vec2;
	std::transform(str.begin(), str.end(), std::back_inserter(vec2),
	 			[](std::string s){ return s.length ();} );
	for( auto&& v: vec2) {
	    cout << v << " ";
	}
	cout << endl;
	 
	//reduce
	std::vector<string> str2 {"Programming", "in", "a", "functional", "style"};
	auto it = std::remove_if (str2.begin(), str2.end(),
	 			  [](std::string s){ return !(std::isupper(s[0]));});
	cout << *it << endl;
	 
	//fold
	std::vector<string> str3 {"Programming", "in", "a", "functional", "style"};
	std::accumulate(str3.begin(), str3.end(), string(""),
	 	    [](std::string a,std::string b){ return a+":"+b; });
	 
	for( auto&& v: str3) {
	    cout << v << " ";
	}
	cout << endl;
	return 0;   
}