如何使用rangev3范围实现flatmap

时间:2016-03-17 04:43:25

标签: c++ c++11 range-v3

我在C ++中为flatmap实现了一个非常简单的std::vector函数,但有人建议范围通常更好。这是基于矢量的解决方案:

// flatmap: [A] -> (A->[B]) -> [B]    
template<typename T, typename FN>
static auto flatmap(const std::vector<T> &vec, FN fn) 
     -> std::vector<typename std::remove_reference<decltype(fn(T())[0])>::type> {
    std::vector<typename std::remove_reference<decltype(fn(T())[0])>::type> result;
    for(auto x : vec) {
        auto y = fn(x);
        for( auto v : y ) {
            result.push_back(v);
        }
    }
    return result;
};

还有人建议我使用迭代器,但这会破坏函数的良好可组合性:

map(filter(flatmap( V, fn), fn2), fn3)

我认为在范围v3世界中,我的目标是将上述内容写成:

auto result = v | flatmap(fn) | filter(fn2) | transform(fn3);

感觉flatmap应该只是views::for_eachyield_fromtransform的微不足道的组合,但我正在努力弄清楚如何将它们连接在一起

3 个答案:

答案 0 :(得分:7)

IIUC,您的flatmap功能只不过是range-v3&#39; s view::for_each。尝试:

using namespace ranges; auto result = v | view::for_each(fn) | to_vector;

HTH

答案 1 :(得分:2)

如果我理解正确,您的函数flatmap必须执行的操作,您可以将其写为v | view::transform(fn) | action::join。以下是使用范围制作它的示例:

#include <range/v3/all.hpp>

#include <iostream>
#include <string>
#include <utility>
#include <vector>


// flatmap: [A] -> (A->[B]) -> [B]
template<typename T, typename FN>
static auto flatmap(const std::vector<T> &vec, FN fn)
     -> std::vector<typename std::remove_reference<decltype(fn(T())[0])>::type> {
    std::vector<typename std::remove_reference<decltype(fn(T())[0])>::type> result;
    for(auto x : vec) {
        auto y = fn(x);
        for( auto v : y ) {
            result.push_back(v);
        }
    }
    return result;
};

// This will be test function for both flatmap and range usage
std::vector<std::string> testFn(int n)
{
    std::vector<std::string> result;
    int ofs = 0;
    for(int i = 0; i < n; ++i)
    {
        char initialChar = 'A' + ofs;
        std::string partialResult = "\"";
        for(int j = 0; j <=i; ++j, ++ofs)
        {
            partialResult.append(1, initialChar+j);
        }
        partialResult += "\"";
        result.push_back(partialResult);
    }
    return std::move(result);
}

int main(int, char**)
{
    std::vector<int> vv {1, 2, 3, 4, 5, 6};
    // test flatmap
    auto r2 = flatmap(vv, testFn);
    for(auto s:r2)
    {
        std::cout << s << " " ;
    }
    std::cout << "\n";

    using namespace ranges;

    // test ranges equivalent
    auto rng = vv|view::transform(testFn)|action::join;
    //         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is an equivalent for flatmap in ranges terms

    for(auto s:rng)
    {
        std::cout << s << " ";
    }
    std::cout << "\n";

    std::cout << std::flush;
    return 0;
}

答案 2 :(得分:1)

两个答案都是正确的,但是我想添加更多上下文,因为for_each的命名可能会有些混乱(确实使我感到困惑)。这是一个示例,您可以用来验证view::for_each实际上是范围的flatMap:

#include <range/v3/all.hpp>
#include <iostream>
#include <vector>
using namespace ranges;

int main()
{
    const std::vector<int> a = { 0, 1, 2 };
    auto b = a | view::for_each([] (int x) { return view::ints(x, x+3); });

   ranges::for_each( b, [] (int x) { std::cout << x << " "; } );
   std::cout << std::endl;
}

这将打印0 1 2 1 2 3 2 3 4。该示例还示出了可能引起混淆的原因,因为在范围名称空间中实际上存在for_each函数,其功能类似于例如。 Java的forEach(即,将函数应用于范围的每个成员而没有返回值)。

如果您查看the documentation of view::for_each,就会发现它是通过transform and join手动实现的。

 auto   operator() (Rng &&rng, Fun fun) const -> decltype(join(transform(static_cast< Rng &&>(rng), std::move(fun))))
相关问题