5 ms·
Nice result :) Btw, it's tempting to use std::function in the same way as you would use a function in Haskell, but it usually isn't a very good idea. In C++ st
by detrino 13y ago
Nice result :)
Btw, it's tempting to use std::function in the same way as you would use a function in Haskell, but it usually isn't a very good idea. In C++ std::function is for when you want type erasure, usually because you wish to store a functor somewhere with a uniform type. Type erasure in C++ is similar to existential typing + a type class in Haskell. You could say that all Haskell closures are implicitly using type erasure and then the compiler has to work hard to optimize away the extra boxing/indirect calls.
Here is another way to write map in C++:
#include <iostream>
#include <list>
template<typename F, typename A, typename B = typename std::result_of<F(A)>::type>
std::list<B> map(std::list<A> const & xs, F f)
{
std::list<B> ys;
for (auto const & x : xs) ys.push_back(f(x));
return ys;
}
int main()
{
std::list<int> xs{1, 2, 3, 4, 5};
auto ys = map(xs, [](int i) { return i * 2; });
for (auto y : ys) std::cout << y << "\n";
}
You can expect this code to run exactly as fast as if you had written the loop by hand instead of using the map template function.
- dllthomas 13y agoYeah, wasn't meant to be idiomatic C++ code, just a simple proof-of-concept. If you'd care to translate it into the former I'd be fascinated to see the result. Playing around a bit, I've been having trouble expressing the type of mbind when I make the function type a parameter to the template. I'm 70% sure it's my failure, not the language, though.