New semester in my university started and I am once again "forced" to quit abstractions and explore the deep waters of low level programming in c++
. My mind is already partially contamined with folds, high order functions, etc., and I don't find any fun in writing for example:
bool allEven = true;
for(int i = 0; i < arr.length; i++){
if (arr[i] % 2 != 0){
allEven = false;
break;
}
}
when I know that I can write val allEven = arr forall (_ % 2 == 0)
.GWT
but instead compiling Java
sources to JavaScript
sources It would compile Scala
or Haskell
or F#
to C++
sources, but since I don't believe that something like this exists, I would like to have something... helpful. I appreciate the suggested anon functions, for example.
Metaprogramming in C is the art of creating new language constructs, typically using macros.
Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself while running.
" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow.
Template meta-programming (TMP) refers to uses of the C++ template system to perform computation at compile-time within the code. It can, for the most part, be considered to be "programming with types" — in that, largely, the "values" that TMP works with are specific C++ types.
It's not entirely clear what you're really asking for, but if you're trying to write C++ that's more like your other code, you could do something like this:
bool allEven =
std::accumulate(arr.begin(), arr.end(), [](bool a, int i) {return a && i & 1==0; }, 1);
This does use a lambda, which is new in C++0x. If you're using an older compiler that doesn't support lambdas, you could look into using Boost Lambda instead (in which case your code would be even closer to the example you've given).
bool is_even = std::find_if(arr.begin(), arr.end(), [](int i) { return i%2 != 0; }) == arr.end();
With new algorithms in C++0x, there is all_of
:
bool all_even = std::all_of(arr.begin(), arr.end(),
[](int i) { return i%2 == 0; });
Boost.Range allows less verbosity:
bool all_even =
0==boost::count_if(arr, [](int i){ return i%2 != 0;});
Hopefully, Boost.Range will soon offer all_of
.
Take a look at Boost.Phoenix library, it enables you to write close(er) to functional style of programming in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With