filter.hpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*!
  2. @file
  3. Forward declares `boost::hana::filter`.
  4. @copyright Louis Dionne 2013-2017
  5. Distributed under the Boost Software License, Version 1.0.
  6. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
  7. */
  8. #ifndef BOOST_HANA_FWD_FILTER_HPP
  9. #define BOOST_HANA_FWD_FILTER_HPP
  10. #include <boost/hana/config.hpp>
  11. #include <boost/hana/core/when.hpp>
  12. BOOST_HANA_NAMESPACE_BEGIN
  13. //! Filter a monadic structure using a custom predicate.
  14. //! @ingroup group-MonadPlus
  15. //!
  16. //! Given a monadic structure and a predicate, `filter` returns a new
  17. //! monadic structure containing only those elements that satisfy the
  18. //! predicate. This is a generalization of the usual `filter` function
  19. //! for sequences; it works for any MonadPlus. Intuitively, `filter` is
  20. //! somewhat equivalent to:
  21. //! @code
  22. //! filter(xs, pred) == flatten(transform(xs, [](auto x) {
  23. //! return pred(x) ? lift<Xs>(x) : empty<Xs>();
  24. //! })
  25. //! @endcode
  26. //! In other words, we basically turn a monadic structure containing
  27. //! `[x1, ..., xn]` into a monadic structure containing
  28. //! @code
  29. //! [
  30. //! pred(x1) ? [x1] : [],
  31. //! pred(x2) ? [x2] : [],
  32. //! ...
  33. //! pred(xn) ? [xn] : []
  34. //! ]
  35. //! @endcode
  36. //! and we then `flatten` that.
  37. //!
  38. //!
  39. //! Signature
  40. //! ---------
  41. //! Given a `MonadPlus` `M` and an `IntegralConstant` `Bool` holding a
  42. //! value of type `bool`, the signature is
  43. //! @f$ \mathtt{filter} : M(T) \times (T \to \mathtt{Bool}) \to M(T) @f$.
  44. //!
  45. //! @param xs
  46. //! The monadic structure to filter.
  47. //!
  48. //! @param pred
  49. //! A function called as `pred(x)` for each element `x` in the monadic
  50. //! structure and returning whether that element should be __kept__ in
  51. //! the resulting structure. In the current version of the library, the
  52. //! predicate has to return an `IntegralConstant` holding a value
  53. //! convertible to a `bool`.
  54. //!
  55. //!
  56. //! Example
  57. //! -------
  58. //! @include example/filter.cpp
  59. #ifdef BOOST_HANA_DOXYGEN_INVOKED
  60. constexpr auto filter = [](auto&& xs, auto&& pred) {
  61. return tag-dispatched;
  62. };
  63. #else
  64. template <typename M, typename = void>
  65. struct filter_impl : filter_impl<M, when<true>> { };
  66. struct filter_t {
  67. template <typename Xs, typename Pred>
  68. constexpr auto operator()(Xs&& xs, Pred&& pred) const;
  69. };
  70. constexpr filter_t filter{};
  71. #endif
  72. BOOST_HANA_NAMESPACE_END
  73. #endif // !BOOST_HANA_FWD_FILTER_HPP