Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@MikaelSmith
Last active December 7, 2015 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikaelSmith/c741d7755cd94671c8c8 to your computer and use it in GitHub Desktop.
Save MikaelSmith/c741d7755cd94671c8c8 to your computer and use it in GitHub Desktop.
Functional C++14 λ Syntax
#include <iostream>
#include <vector>
template <typename T, typename... TArgs, template <typename...>class C, typename F>
auto fn_map(const C<T,TArgs...>& container, const F& f) {
using resultType = decltype(f(std::declval<T>()));
C<resultType> result;
for (const auto& item : container)
result.push_back(f(item));
return result;
}
template <typename TResult, typename T, typename... TArgs,
template <typename...>class C, typename F>
TResult fn_reduce(const C<T,TArgs...>& container, const TResult& startValue, const F& f)
{
TResult result = startValue;
for (const auto& item : container)
result = f(result, item);
return result;
}
template <typename T, typename... TArgs, template <typename...>class C, typename F>
C<T,TArgs...> fn_filter(const C<T,TArgs...>& container, const F& f)
{
C<T,TArgs...> result;
for (const auto& item : container)
if (f(item))
result.push_back(item);
return result;
}
#define λ(x) [](auto _1){ return (x); }
#define λ2(x) [](auto _1, auto _2){ return (x); }
int main()
{
using namespace std;
vector<int> x{1, 2, 3, 4, 5};
auto even = fn_filter(x, λ(_1 % 2 == 0));
for(auto &&x : even) {
cout << x << endl;
}
cout << fn_reduce(even, 0, λ2(_1 + _2)) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment