the_yap_way.qbk 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. [section The YAP Way]
  2. There are certain idioms that _yap_ is written to support. Before getting
  3. into the nuts and bolts of how _yap_ operates, let's define these idioms.
  4. [heading _eval_xform_]
  5. This is the main idiom you'll see reinforced in the examples. The idea is
  6. that you capture an expression:
  7. auto expr_0 = /* ... */ ;
  8. then transform it one or more times:
  9. auto expr_1 = boost::yap::transform(expr_0, my_transform_1);
  10. auto expr_2 = boost::yap::transform(expr_1, my_transform_2);
  11. // ...
  12. auto expr_n = boost::yap::transform(expr_n_minus_1, my_transform_n);
  13. and then finally you evaluate it:
  14. auto const result = boost::yap::evaluate(expr_n);
  15. Each call to _xform_ here produces a new _Expr_ that can subsequently be
  16. transformed. This is conceptually similar to what happens inside many
  17. compilers. Capturing the expression is analogous to the compiler's parse; the
  18. transformations are analogous to optimization passes; and the evaluation is
  19. analogous to code generation.
  20. This keeps the meaning of your code quite clear and easy to follow. For this
  21. reason, I think you should try to use _yap_ in this way when you can.
  22. [heading _xform_as_eval_]
  23. This is a variant of _eval_xform_, where the _eval_ call at the end is
  24. unnecessary, because the final (or perhaps only) transform does all the
  25. evaluation we need.
  26. For instance, here is the `get_arity` transform object used in the _calc3_
  27. example (don't worry too much about the implementation _emdash_ we'll return
  28. to this later in the docs in much greater detail):
  29. [calc3_get_arity_xform]
  30. Here is how this might be used:
  31. auto expr = 1_p * 2_p;
  32. auto const arity = boost::yap::transform(expr, get_arity{});
  33. static_assert(arity.value == 2, "Called with wrong number of args.");
  34. In this case, _xform_ produces a non-_Expr_ value, all by itself. We got our
  35. result without ever needing to call _eval_.
  36. [note Whether _xform_ returns an _Expr_ or non-_Expr_ is entirely up to the
  37. caller. The transform object passed as the second argument to _xform_ defines
  38. what _xform_'s return type will be.]
  39. [endsect]