mapcar in C++11
-
Ich würde gerne mapcar aus Lisp in C++11 implementieren:
template <typename ListType, typename Map> ListType mapcar(Map LambdaFunction, const ListType& List) { ListType result; transform(List.begin(), List.end(), back_inserter(result), LambdaFunction); return result; }Geht das besser?
-
Also ich versteh nicht ganz warum du das nochmal in eine extra Funktion packen willst, wenn du mit
std::transformsowieso das Ergebnis erreichen kannst.Außerdem, was ist wenn dein Listentyp keinen
std::back_inserterunterstützt, wie z.B.std::queue?
-
weil ich transform nicht kannte

-
Und was ist hier falsch:
template <typename InputListType, typename OutputListType, typename Map> OutputListType mapcar(Map LambdaFunction, const InputListType& liste) { OutputListType result; for (const auto elt: liste) result.push_back(LambdaFunction(elt)); return result; } int main() { vector<int> a({1,2,3,4,5}); vector<double> b = mapcar([](int i) -> double{return i*2.5;}, a); for (auto const elt: b) cout << elt << " "; return 0; }error: conversion from ‘std::vector<int>’ to non-scalar type ‘std::vector<double>’ requested|
||=== Build finished: 1 errors, 0 warnings ===|"
-
Ok das ist verwunderlich weil du es ja in deinem Ausgangspost verwendest

-
huuuuuuuuuuuu schrieb:
error: conversion from ‘std::vector<int>’ to non-scalar type ‘std::vector<double>’ requested|
||=== Build finished: 1 errors, 0 warnings ===|Ist das nicht ziemlich eindeutig? Du kannst keinen vector<int> einfach durch Zuweisung in einen vector<double> konvertieren!
-
Aber mein mapcar hat doch extra dafür einen OutputListType.
-
vector<double> b = mapcar<vector<double> >([](int i) -> double {return i*2.5;}, a);so funzt es.
-
Wieso meckert er eigentlich nicht schon an der Stelle, an der er es nicht schafft, für OutputListType einen Typen herzuleiten?

-
Wofür steht eigentlich "mapcar"?
-
314159265358979 schrieb:
template <typename T> T make(); template <typename InType, typename Function> auto mapcar(std::vector<InType> const& in, Function const& func) -> std::vector<decltype(func(make<InType>()))> { typedef decltype(func(make<InType>())) OutType; // ... }Warum einfach, wenns auch kompliziert geht

template <typename InType, typename Function, typename OutType = typename std::result_of<Function(InType)>::type > std::vector<OutType> mapcar(std::vector<InType> const& in, Function const& func) { // ... }BTW: mapcar kommt von map wie mappen und car wie CAR
-
Weil ich daran halt nicht gedacht habe. Du hättest es ja selbst posten können, wenn du so schlau bist.

-
std__result_of schrieb:
BTW: mapcar kommt von map wie mappen und car wie CAR
Hihi, was für eine Abkürzung: "Contents of the Address part of Register number". Zweck sofort ersichtlich

-
car,cdr,cadr,cadadr, ... aber wahrscheinlich sind die meisten zu jung dafuer.