where-pick.cc 1.3 KB

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