如何使用rangev3范围实现flatmap

Mic*_*son 8 c++ c++11 range-v3

我有一个非常简单的flatmap函数在C++中实现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;
};
Run Code Online (Sandbox Code Playgroud)

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

map(filter(flatmap( V, fn), fn2), fn3)
Run Code Online (Sandbox Code Playgroud)

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

auto result = v | flatmap(fn) | filter(fn2) | transform(fn3);
Run Code Online (Sandbox Code Playgroud)

感觉flatmap应该只是一个微不足道的组合views::for_each,yield_from而且transform,我正在努力找出如何将它们连接在一起.

Eri*_*ler 8

IIUC,你的flatmap功能不过是range-v3 view::for_each.尝试:

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

HTH


use*_*083 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;
}
Run Code Online (Sandbox Code Playgroud)