public
Last active

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++.

  • Download Gist
monoid.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.