basics.qbk 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. [/==============================================================================
  2. Copyright (C) 2001-2010 Joel de Guzman
  3. Copyright (C) 2001-2005 Dan Marsden
  4. Copyright (C) 2001-2010 Thomas Heller
  5. Distributed under the Boost Software License, Version 1.0. (See accompanying
  6. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. ===============================================================================/]
  8. [section Basics]
  9. [def __constant_n__ /n/]
  10. [def __argument_n__ a/n/]
  11. Almost everything is a function in the Phoenix library that can be evaluated as
  12. `f(a1, a2, ..., __argument_n__)`, where __constant_n__ is the function's arity, or number of arguments that the
  13. function expects. Operators are also functions. For example, `a + b` is just a
  14. function with arity == 2 (or binary). `a + b` is the same as `add(a, b)`, `a + b
  15. + c` is the same as `add(add(a, b), c)`.
  16. [note Amusingly, functions may even return functions. We shall see
  17. what this means in a short while.]
  18. [heading Partial Function Application]
  19. Think of a function as a black box. You pass arguments and it returns something
  20. back. The figure below depicts the typical scenario.
  21. [$images/fbox.png]
  22. A fully evaluated function is one in which all the arguments are given. All
  23. functions in plain C++ are fully evaluated. When you call the `sin(x)` function,
  24. you have to pass a number x. The function will return a result in return: the
  25. sin of x. When you call the `add(x, y)` function, you have to pass two numbers x
  26. and y. The function will return the sum of the two numbers. The figure below is
  27. a fully evaluated `add` function.
  28. [$images/adder.png]
  29. A partially applied function, on the other hand, is one in which not all the
  30. arguments are supplied. If we are able to partially apply the function `add`
  31. above, we may pass only the first argument. In doing so, the function does not
  32. have all the required information it needs to perform its task to compute and
  33. return a result. What it returns instead is another function, a lambda function.
  34. Unlike the original `add` function which has an arity of 2, the resulting lambda
  35. function has an arity of 1. Why? because we already supplied part of the input:
  36. `2`
  37. [$images/add2.png]
  38. Now, when we shove in a number into our lambda function, it will return 2 plus
  39. whatever we pass in. The lambda function essentially remembers 1) the original
  40. function, `add`, and 2) the partial input, 2. The figure below illustrates a
  41. case where we pass 3 to our lambda function, which then returns 5:
  42. [$images/add2_call.png]
  43. Obviously, partially applying the `add` function, as we see above, cannot be
  44. done directly in C++ where we are expected to supply all the arguments that a
  45. function expects. That's where the Phoenix library comes in. The library
  46. provides the facilities to do partial function application.
  47. And even more, with Phoenix, these resulting functions won't be black boxes
  48. anymore.
  49. [heading STL and higher order functions]
  50. So, what's all the fuss? What makes partial function application so useful?
  51. Recall our original example in the [link phoenix.starter_kit.lazy_operators
  52. previous section]:
  53. std::find_if(c.begin(), c.end(), arg1 % 2 == 1)
  54. The expression `arg1 % 2 == 1` evaluates to a lambda function. `arg1` is a
  55. placeholder for an argument to be supplied later. Hence, since there's only one
  56. unsupplied argument, the lambda function has an arity 1. It just so happens that
  57. `find_if` supplies the unsupplied argument as it loops from `c.begin()` to
  58. `c.end()`.
  59. [note Higher order functions are functions which can take other
  60. functions as arguments, and may also return functions as results. Higher order
  61. functions are functions that are treated like any other objects and can be used
  62. as arguments and return values from functions.]
  63. [heading Lazy Evaluation]
  64. In Phoenix, to put it more accurately, function evaluation has two stages:
  65. # Partial application
  66. # Final evaluation
  67. The first stage is handled by a set of generator functions. These are your front
  68. ends (in the client's perspective). These generators create (through partial
  69. function application), higher order functions that can be passed on just like
  70. any other function pointer or function object. The second stage, the actual
  71. function call, can be invoked or executed anytime in the future, or not at all;
  72. hence /"lazy"/.
  73. If we look more closely, the first step involves partial function application:
  74. arg1 % 2 == 1
  75. The second step is the actual function invocation (done inside the `find_if`
  76. function. These are the back-ends (often, the final invocation is never actually
  77. seen by the client). In our example, the `find_if`, if we take a look inside,
  78. we'll see something like:
  79. template <class InputIterator, class Predicate>
  80. InputIterator
  81. find_if(InputIterator first, InputIterator last, Predicate pred)
  82. {
  83. while (first != last && !pred(*first)) // <--- The lambda function is called here
  84. ++first; // passing in *first
  85. return first;
  86. }
  87. Again, typically, we, as clients, see only the first step. However, in this
  88. document and in the examples and tests provided, don't be surprised to see the
  89. first and second steps juxtaposed in order to illustrate the complete semantics
  90. of Phoenix expressions. Examples:
  91. int x = 1;
  92. int y = 2;
  93. std::cout << (arg1 % 2 == 1)(x) << std::endl; // prints 1 or true
  94. std::cout << (arg1 % 2 == 1)(y) << std::endl; // prints 0 or false
  95. [heading Forwarding Function Problem]
  96. Usually, we, as clients, write the call-back functions while libraries (such as
  97. STL) provide the callee (e.g. `find_if`). In case the role is reversed, e.g.
  98. if you have to write an STL algorithm that takes in a predicate, or develop a
  99. GUI library that accepts event handlers, you have to be aware of a little known
  100. problem in C++ called the "__forwarding__".
  101. Look again at the code above:
  102. (arg1 % 2 == 1)(x)
  103. Notice that, in the second-stage (the final evaluation), we used a variable `x`.
  104. In Phoenix we emulated perfect forwarding through preprocessor macros generating
  105. code to allow const and non-const references.
  106. We generate these second-stage overloads for Phoenix expression up to
  107. `BOOST_PHOENIX_PERFECT_FORWARD_LIMIT`
  108. [note You can set `BOOST_PHOENIX_PERFECT_FORWARD_LIMIT`, the predefined maximum perfect
  109. forward arguments an actor can take. By default, `BOOST_PHOENIX_PERFECT_FORWARDLIMIT`
  110. is set to 3.]
  111. [/
  112. Be aware that the second stage cannot accept non-const temporaries and literal
  113. constants. Hence, this will fail:
  114. (arg1 % 2 == 1)(123) // Error!
  115. Disallowing non-const rvalues partially solves the "__forwarding__" but
  116. prohibits code like above.
  117. ]
  118. [heading Polymorphic Functions]
  119. Unless otherwise noted, Phoenix generated functions are fully polymorphic. For
  120. instance, the `add` example above can apply to integers, floating points, user
  121. defined complex numbers or even strings. Example:
  122. std::string h("Hello");
  123. char const* w = " World";
  124. std::string r = add(arg1, arg2)(h, w);
  125. evaluates to `std::string("Hello World")`. The observant reader might notice
  126. that this function call in fact takes in heterogeneous arguments where `arg1`
  127. is of type `std::string` and `arg2` is of type `char const*`. `add` still works
  128. because the C++ standard library allows the expression `a + b` where `a` is a
  129. `std::string` and `b` is a `char const*`.
  130. [endsect]