Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
List comprehension in C++ using functional patterns
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//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'; } }
clang++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.83 sec, absolute running time: 0.09 sec, cpu time: 0.02 sec, memory peak: 3 Mb, absolute service time: 0,93 sec
edit mode
|
history
|
discussion
1 4 9