where.C 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Daniel Llorens - 2015
  2. // Adapted from blitz++/examples/where.cpp
  3. #include "ra/operators.H"
  4. #include "ra/io.H"
  5. #include "ra/test.H"
  6. using std::cout; using std::endl; using std::flush;
  7. int main()
  8. {
  9. ra::Big<int, 1> x = ra::iota(7, -3); // [ -3 -2 -1 0 1 2 3 ]
  10. // The where(X,Y,Z) function is similar to the X ? Y : Z operator.
  11. // If X is logical true, then Y is returned; otherwise, Z is
  12. // returned.
  13. ra::Big<int, 1> y = where(abs(x) > 2, x+10, x-10);
  14. // The above statement is transformed into something resembling:
  15. //
  16. // for (unsigned i=0; i < 7; ++i)
  17. // y[i] = (abs(x[i]) > 2) ? (x[i]+10) : (x[i]-10);
  18. //
  19. // The first expression (abs(x) > 2) can involve the usual
  20. // comparison and logical operators: < > <= >= == != && ||
  21. cout << x << endl << y << endl;
  22. // In ra:: we can also pick() among more than two values. You can
  23. // put anything in the selector expression (the first argument) that will
  24. // evaluate to an argument index.
  25. ra::Big<int, 1> z = pick(where(x<0, 0, where(x==0, 1, 2)), x*3, 77, x*2);
  26. TestRecorder tr(std::cout, TestRecorder::NOISY);
  27. tr.test_eq(ra::start({7, -12, -11, -10, -9, -8, 13}), y);
  28. tr.test_eq(ra::start({-9, -6, -3, 77, 2, 4, 6}), z);
  29. return tr.summary();
  30. }