Skip to content

Instantly share code, notes, and snippets.

@joshburgess
Forked from carymrobbins/tc.cpp
Created September 26, 2019 05:44
Show Gist options
  • Save joshburgess/674708458e17febd36e2cb0721608fba to your computer and use it in GitHub Desktop.
Save joshburgess/674708458e17febd36e2cb0721608fba to your computer and use it in GitHub Desktop.
An example of implementing type classes in C++.
/*
To compile and run -
% g++ tc.cpp -std=c++11 -o tc
% ./tc
2, 4, 6, 8
*/
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <template <class, class...> class f>
struct functor {
template<typename a, typename b>
static f<b>* map(const f<a>* fa, function<b(a)> ab);
};
template<>
struct functor<vector> {
template<typename a, typename b>
static vector<b>* map(const vector<a>* va, function<b(a)> ab) {
vector<b>* vb = new vector<b>(va->size());
for (unsigned i = 0; i < va->size(); ++i) {
const a aval = (*va)[i];
const b bval = ab(aval);
(*vb)[i] = bval;
}
return vb;
}
};
int main(int argc, char** argv) {
vector<int> vi { 1, 2, 3, 4 };
vector<string>* vs = functor<vector>::map<int, string>(&vi, [](int i) { return to_string(i*2); });
for (auto it = vs->begin(); it < vs->end(); ++it) {
if (it > vs->begin()) cout << ", ";
cout << *it;
}
cout << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment