//clang 3.8.0
#include <iostream>
#include <list>
#include <iterator>
#include <type_traits>
#include <algorithm>
// example of applying the monad pattern to create a list comprehension like structure in C++
/*
The list monad
*/
//The unit list containing 'a'
let unit : 'a -> 'a t = fun a -> [a]
template <class A>
std::list<A> unit (A const& a) { return std::list<A> (1u, a); }
//The 'bind' operator
let rec ( * ) : 'a t -> ('a -> 'b t) -> 'b t =
fun l -> fun k ->
match l with | [] -> [] | (h :: tl) -> k h @ tl * k
template <class A, class F>
typename std::result_of<F(A)>::type
operator * (std::list<A> a, F k) {
typedef typename std::result_of<F(A)>::type result_t;
if (a.empty ())
return result_t ();
result_t res = k (a.front ());
a.pop_front ();
clang++
1 4 9