4 ms·
At first I wondered why he calls the monadic flatmap operation "for_each" but it makes sense in that he's actually creating a (lazy) list comprehension DSL here
by Sharlin 8y ago
At first I wondered why he calls the monadic flatmap operation "for_each" but it makes sense in that he's actually creating a (lazy) list comprehension DSL here. The code within main() is mostly equivalent to the following Python code:
triples = ((a, b, c) for c in itertools.count()
for a in range(1, c+1)
for b in range(a, c+1)
if a*a + b*b == c*c)
for (a,b,c) in itertools.islice(triples, 10):
print("{}, {}, {}".format(a,b,c))
The equivalent in Rust, just because I'm currently learning it:
let triples = (1..)
.flat_map(move |c| (1..=c)
.flat_map(move |a| (a..=c)
.flat_map(move |b| Some((a, b, c))
.filter(|_| a*a + b*b == c*c))));
for (a,b,c) in triples.take(10) {
println!("{}, {}, {}", a, b, c)
}
- blub 8y agoI was anyway thinking that his example looked incomprehensible, but your Python example makes a complete mockery of it. The difference is night and day, I'm dismayed at how horrible that C++ code is, hope I never have to deal with such crap.
- Sharlin 8y agoThe big difference is that it's a pure library solution in C++. The code inside main is not too bad once you have the building blocks in place (implemented in a library, of course, not by yourself).
- mehrdadn 8y ago> but your Python example makes a complete mockery of it. I mean, try getting the same kind of performance and static verification in Python? So much of the complexity of C++ is due to the static typing and the optimizations that can come with it. If you're willing to give up and make everything dynamic then of course it'll simplify your code, but you get a massive penalty both in terms of performance and in terms of error-checking.
- Sharlin 8y agoUpvoted, but to be fair, Rust shows that expressiveness and performance aren't mutually exclusive. It does not (currently) have language-level list comprehensions, but those could be easily enough implemented as simple syntactic transformations over the existing iterator combinators, the way Scala does it.
- mehrdadn 8y agoThanks, yeah, I was very careful to avoid claiming they're mutually exclusive. However, although I stopped trying to learn Rust back in 2016, unless it's changed its fundamentals radically (which I understand it hasn't), I'm not sure if it's really a counterexample here for expressiveness. Can you use different allocators for different vectors in the same function in Rust? Can you have custom move semantics for objects that might know about pointers to them? And does the compiler no longer complain about code that really should work just fine? [1] I understand the answers to most if not all such questions is still "no", at which point I stop believing it really has the same flexibility as C++ or the same ease of writing as Python, but would be happy to hear if things have changed. [1] http://softwaremaniacs.org/blog/2016/02/12/ownership-borrowing-hard/en/ http://softwaremaniacs.org/blog/2016/02/12/ownership-borrowi...
- couchand 8y ago> And does the compiler no longer complain about code that really should work just fine? In the general case that's theoretically impossible, and also not really a good measure anyway.
- mehrdadn 8y agoOkay, how about in the practical cases that actually come up and make you have to work around the compiler?
- Sharlin 8y agoNon-lexical lifetimes, which were just recently stabilized [1], make many of the most common cases of borrow checker frustration "just work". And now that the groundwork is done, even more cases will likely be supported in the future. [1] https://rust-lang-nursery.github.io/edition-guide/rust-2018/ownership-and-lifetimes/non-lexical-lifetimes.html https://rust-lang-nursery.github.io/edition-guide/rust-2018/...
- hellofunk 8y agoThe trade-offs between the two languages are so huge, and you seem unaware of what those trade-offs are.
- Veedrac 8y agoFWIW, overly long iterator comprehensions, or unwieldy chains of them, are common in Python, but a local generator function is much cleaner most of the time in my experience. The difference is slight here but the rule of thumb never goes wrong for me. Splitting the logic out into a generator function tends to make the flow more readable, and it becomes easier to make changes to the logic or add intermediate filters or variables.
- tromp 8y agoOr in Haskell: triples = [(a,b,c) | c <- [1..], a <- [1..c], b <- [a..c], a*a + b*b == c*c] mapM_ print $ take 10 triples
- klyrs 8y agoslavik81 showed a simpler for_each in a comment; auto for_each = [](R&& r, Fun fun) { return r | view::transform(fun) | view::join; }; similarly, it seems that yield_if can also be radically simplified auto yield_if = []<Semiregular T>(bool b, T x) { return b ? view::single(x) : view::empty<T>; }; But if you actually read the blog post... for_each and yield_if are a part of the range_v3 library and are proposed additions to the language. Also I don't know what the heck is up with that cout statement; we can use structured declarations to make that look more pythonic too. And there's also a proposal for string formatting [1] #include "fmt/format.h" #include <iostream> #include <ranges> using namespace std; using namespace view; using namespace fmt; int main() { auto triples = for_each(iota(1), [](int z) { return for_each(iota(1, z+1), [=](int x) { return for_each(iota(x, z+1), [=](int y) { return yield_if(x*x + y*y == z*z, make_tuple(x, y, z)); }); }); }); for(auto [x,y,z] : triples | take(10)) cout << format("{}, {}, {}", a, b, c) << endl; } So despite all the protests about how ugly Eric's solution is... I don't think the above is significantly worse than your python & rust equivalents. Speaking as a python evangelist who uses C++ out of nece$$ity. [1] https://github.com/fmtlib/fmt https://github.com/fmtlib/fmt