mardi 8 décembre 2015

Writing a simple map function using lambdas

I am trying to better understand lambdas and the algorithm library by implementing a simple map (ala Clojure) function. I'm getting a variety of odd compilation errors, sometimes from my own code and other times from within the algorithm library, and I'd like to know why. Here are all the various iterations of my attempt and the different errors and questions they create:

template <typename T, typename Func>
std::vector<T> map(Func f, std::vector<T> coll){
    std::vector<T> ret;
    std::transform(coll.begin(), coll.end(), ret.begin(),f);
    return ret;
}

This creates one compilation error in algorithm:

template <class _InputIterator, class _OutputIterator, class _UnaryOperation>
inline _LIBCPP_INLINE_VISIBILITY
_OutputIterator
transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op)
{
    for (; __first != __last; ++__first, (void) ++__result)
        *__result = __op(*__first); // <--- No viable overloaded '='
    return __result;
}

This error is not clear to me. I decided that maybe my strategy for doing this is not descriptive enough, so I tried to make it into an explicit lambda using whatever is passed in:

template <typename T, typename Func>
std::vector<T> map(Func f, std::vector<T> coll){
    std::vector<T> ret;
    std::transform(coll.begin(), coll.end(), ret.begin(),
                   [&f](auto x)->(T) {return f(x);});
    return ret;
}

Now a new compilation error on my map function, saying:

Expected a type on my (T)

Since I want the function to return a new value of the same type of the vector element, I thought this was how to write a return value in a lambda. However, I have seen lambda examples at various websites that show the return type either with or without the parenthesis, so I changed the lambda to this:

[&f](auto x)->T {return f(x);}

This seemingly trivial change created a whole new compiler error:

enter image description here

So basically, I'd like some help understanding these various errors and how they relate to the lambda syntax and the function template I am attempting.

Aucun commentaire:

Enregistrer un commentaire