Skip to content

Instantly share code, notes, and snippets.

@valkheim
Created February 15, 2018 18:12
Show Gist options
  • Save valkheim/5f9834305ba3b6276abb437fc5418ef6 to your computer and use it in GitHub Desktop.
Save valkheim/5f9834305ba3b6276abb437fc5418ef6 to your computer and use it in GitHub Desktop.
functionnal c++
#include <vector>
#include <numeric>
#include <cstdio>
auto foldable(auto col) {
return [col](auto f, auto initial) {
return std::accumulate(col.begin(), col.end(), initial, f);
};
}
auto map(auto foldable, auto f) {
return [foldable, f](auto r, auto initial) {
return foldable([r, f](auto accum, auto x) {
return r(accum, f(x));
}, initial);
};
}
auto filter(auto foldable, auto p) {
return [foldable, p](auto r, auto initial) {
return foldable([r, p](auto accum, auto x) {
return p(x) ? r(accum, x) : accum;
}, initial);
};
}
int inc(int x) {
return x + 1;
}
bool odd(int x) {
return x % 2;
}
auto push(std::vector<int>* vec, int item) {
vec->push_back(item);
return vec;
}
int main() {
auto v = std::vector<int>{1, 2, 3, 4};
auto c = filter(map(foldable(v), inc), odd);
//auto c = filter(map(foldable(v), inc), [](int x){return x % 2;});
auto v2 = std::vector<int>{};
c(push, &v2);
for(auto x : v2) {
printf("%d ", x);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment