Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
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
marquee text in C++
001
Apple is not convertible to itself (clang 3.8.0)
le regime keto aviss
A
Test size_t
Example Node Program
BinaryGap, C++ - Find longest sequence of zeros in binary representation of an integer.
Throttle Example in C++
Narrowing error