How to do it...

To implement the map function you should:

  • Use std::transform on containers that support iterating and assignment to the elements, such as std::vector or std::list:
        template <typename F, typename R> 
R mapf(F&& f, R r)
{
std::transform(
std::begin(r), std::end(r), std::begin(r),
std::forward<F>(f));
return r;
}
  • Use other means such as explicit iteration and insertion for containers that do not support assignment to the elements, such as std::map:
        template<typename F, typename T, typename U> 
std::map<T, U> mapf(F&& f, std::map<T, U> const & m)
{
std::map<T, U> r;
for (auto const kvp : m)
r.insert(f(kvp));
return r;
}

template<typename F, typename T>
std::queue<T> mapf(F&& f, std::queue<T> q)
{
std::queue<T> r;
while (!q.empty())
{
r.push(f(q.front()));
q.pop();
}
return r;
}

To implement the fold function you should:

  • Use std::accumulate() on containers that support iterating:
        template <typename F, typename R, typename T> 
constexpr T foldl(F&& f, R&& r, T i)
{
return std::accumulate(
std::begin(r), std::end(r),
std::move(i),
std::forward<F>(f));
}

template <typename F, typename R, typename T>
constexpr T foldr(F&& f, R&& r, T i)
{
return std::accumulate(
std::rbegin(r), std::rend(r),
std::move(i),
std::forward<F>(f));
}
  • Use other means to explicitly process containers that do not support iterating, such as std::queue:
        template <typename F, typename T> 
constexpr T foldl(F&& f, std::queue<T> q, T i)
{
while (!q.empty())
{
i = f(i, q.front());
q.pop();
}
return i;
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset