Created
December 15, 2012 10:06
-
-
Save fthomas/4292455 to your computer and use it in GitHub Desktop.
A C++ monoid trait. Example code shamelessly copied from http://www.scala-lang.org/node/114 .
This is just an experiment, how the linked Scala code can be translated into C++.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <iterator> | |
#include <list> | |
#include <string> | |
using namespace std; | |
template<class T> | |
struct Semigroup { | |
static T add(const T& a, const T& b) { | |
return a + b; | |
} | |
}; | |
template<class T> | |
struct Monoid : Semigroup<T> { | |
static T unit(); | |
}; | |
template<> | |
struct Monoid<int> : Semigroup<int> { | |
static int unit() { return 0; } | |
}; | |
template<> | |
struct Monoid<string> : Semigroup<string> { | |
static string unit() { return ""; } | |
}; | |
template<class InputIt, | |
class T = typename iterator_traits<InputIt>::value_type> | |
T sum(InputIt first, InputIt last) { | |
return accumulate(first, last, Monoid<T>::unit(), Monoid<T>::add); | |
} | |
int main() { | |
auto l1 = list<int>{1, 2, 3}; | |
auto l2 = list<string>{"a", "b", "c"}; | |
auto l3 = list<char>{'a', 'b', 'c'}; | |
cout << sum(begin(l1), end(l1)) << endl; | |
cout << sum(begin(l2), end(l2)) << endl; | |
//cout << sum(begin(l3), end(l3)) << endl; // does not compile | |
// undefined reference to `Monoid<char>::unit()' | |
} | |
// $ g++ -std=c++11 monoid.cpp | |
// $ ./a.out | |
// 6 | |
// abc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment