Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Blog
List comprehension in C++ using functional patterns
//clang 3.8.0 #include <iostream> #include <list> #include <iterator> #include <type_traits> #include <algorithm> #include <iostream> // 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 (); res.splice (res.end (), a * k); return res; } int main() { //l = [1, 2, 3] std::list<int> l = {1, 2, 3}; //m = [1, 4, 9] auto m = l * [](int x) { return unit (float (x * x)); }; for (int n : m) { std::cout << n << '\n'; } }
run
|
edit
|
history
|
help
0
Please
log in
to post a comment.
Thread-safe Interval Average Calculator
program_4
void pointer
Rounding float to nearest 1000 (fixed)
template specialization inheritance problem
Saam hash example
virtual members
Result of not joining thread in main()
illegal instruction (SIGILL)
Делим на Ноль
Please log in to post a comment.