4 ms·
Reading these I'm struck by the non-orthogonality and "mental compilation" on display here. In Python instead of return numbers.end() != std::f
by kragen 5y ago
Reading these I'm struck by the non-orthogonality and "mental compilation" on display here. In Python instead of
return numbers.end()
!= std::find_if(numbers.begin(), numbers.end(),
[](int number) { return number % 2 == 1; });
I would write
return any(number % 2 == 1 for number in numbers)
which, similarly, stops examining numbers once it finds an odd one, but works by transforming the sequence of numbers into a lazy sequence of booleans, then applying the generic boolean-sequence-reducer `any` to it. I think this more clearly says what is desired (the C++ version strikes me as something a compiler might output given the Python version, but in this case you had to run the compiler in your mind), and additionally is a better orthogonal decomposition of the problem than computing a first-hit iterator from a sequence of numbers and a number-to-boolean transformation, then comparing it against the end of the sequence.
Sandor's suggested replacement solves the first problem of clearly saying what is desired:
return std::any_of(numbers.begin(), numbers.end(),
[](int number) { return number % 2 == 1; });
But the penalty is even worse orthogonality!
Because of Python's better orthogonality, you can factor out the lazy boolean sequence generator into a function of its own if that's a useful thing to do:
def oddnesses(numbers):
return (number % 2 == 1 for number in numbers)
return any(oddnesses(numbers))
In this particular case the extra degree of composability you get from it is not very useful, but then again, neither is the original code. You could do things like this with that sequence with equal plausibility to the original code:
all(oddnesses(numbers)) # addressed by all_of in OP
zip(numbers, oddnesses(numbers))
sum(oddnesses(numbers)) # punning booleans as ints
sum(map(operator.mul, numbers, oddnesses(numbers)))
Of course, Python is not really a viable alternative to C++ in most of the places where people are using C++, mostly because it uses 40 times as much CPU and energy and 10 times as much memory, but also because large Python codebases get unmaintainable.
But we could wish for a language with the efficiency and in-the-large maintainability of C++ and the clarity and generality of Python.
- eska 5y agoAre you aware of ranges? std::ranges::any_of(numbers, [](auto i){ return i % 2 == 0; })) There's also stuff like this for orthogonality https://en.cppreference.com/w/cpp/ranges/transform_view https://en.cppreference.com/w/cpp/ranges/transform_view
- kragen 5y agoYes, which is why I complained about how nonorthogonal the C++ was instead of just how verbose :)
- eska 5y agoSee my edit. You're probably interested in views, with which you can do stuff similar to lazy functional languages v | std::views::reverse | std::views::drop(2); Here's an intro https://hannes.hauswedell.net/post/2019/11/30/range_intro/ https://hannes.hauswedell.net/post/2019/11/30/range_intro/
- blt 5y agoSadly the C++20 ranges library does not include any facility to create views by writing Python-like generator loops (coroutine loops with "yield"). Creating new views is about as difficult as creating iterators before - i.e. too difficult.
- eska 5y agoThen your complaint is not orthogonality. Orthogonality means that you can use a for each loop, find_if, any_of, ranges::any_of and everything will still compose the same no matter where the data comes from (file, network, a function that advances an iterator). Your complaint seems to be that iterators instead of coroutines are used here.
- jrimbault 5y agoBecause I love Python, and Rust is applicable is many places where C++ is, here's a Rust version : // assuming `numbers` is an iterator numbers.any(|i| i % 2 == 1) Rust's iterators generally compile down very well, and I think this exactly as expressive as Python. And I also wished C#'s Enumerable were as performant as Rust's iterators.
- Doctor_Fegg 5y agoThat’s basically borrowed off Ruby. (Which isn’t a bad thing.)
- kragen 5y agoIt's not that simple. Ruby's Enumerable is a concrete class; Rust's std::iter::Iterator is a trait, which has some aspects in common with Ruby classes and other aspects in common with Python protocols such as the Python iterator protocol. std::iter::Iterator is (primarily, though not in this case) an external iterator like Python iterators, STL iterators, and ranges in C++20 or D, not an internal iterator like (the original version of) Ruby Enumerable. Rust's type-checking strategy is more like ML than like Ruby, Python, C++, or D, while its compilation strategy is more like C++'s or D's compilation strategy than those of Ruby, Python, or ML.
- Zababa 5y agoThe closure syntax is noted in the "influences" page of the language reference: https://doc.rust-lang.org/reference/influences.html https://doc.rust-lang.org/reference/influences.html > Ruby: closure syntax
- mbrubeck 5y agoAnd if you write the equivalent to the `find_if` version in Rust, then the standard linter Clippy will automatically suggest the "good" version: warning: called `is_some()` after searching an `Iterator` with `find` --> src/lib.rs:2:9 | 2 | numbers.find(|i| i % 2 == 1).is_some() | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `any()` instead: `any(|i| i % 2 == 1)` |
- 5y ago
- jackewiehose 5y agoin C++ I would write for (int i: numbers) if (i % 2 == 1) return true; return false; find_if() etc. is fine if you already have the right predicate function at hand but it becomes quite ridiculous with lambda expressions.
- secondcoming 5y agoThis interestingly generates shorter code as the compiler doesn't attempt any loop unrolling https://godbolt.org/z/eebE9eYP6 https://godbolt.org/z/eebE9eYP6
- kragen 5y agoI probably would too, and composability would suffer further. The concern you raise about lambda expressions is basically one of syntax rather than semantics. Syntax is important, but as an unrepentant user and occasional implementor of Lisps and Forths, I am in no position to criticize C++ :)
- Zababa 5y agoWhat I like about your example is that it's way better at communicating intent than the other C++ examples. In JS I would probably use numbers.some(number => (number % 2) === 1) I feel like the other C++ examples given are noisy.
- tomsmeding 5y ago> But we could wish for a language with the efficiency and in-the-large maintainability of C++ and the clarity and generality of Python. What about Haskell? Maintainability yes; efficiency mostly. It has a GC that can be a pain for high-memory scenarios if you don't spend a lot of effort optimising, but on the whole Haskell is surprisingly fast for its expressivity. Any odd? `any odd numbers`. Or equivalently, `or (map odd numbers)`, which is compositional in that `map odd numbers` is just a list again -- no distinction between lazy and strict lists in Haskell. Your other four examples are `and (map odd numbers)`, `zip numbers (map odd numbers)`, `sum (map (fromEnum . odd) numbers)`, `sum (zipWith (*) numbers (map (fromEnum . odd) numbers))`. Note I used `map odd` instead of defining `oddnesses = map odd` and using `oddnesses`, because the definition is shorter than the name. :) This changes somewhat when you use arrays instead of lists: Haskell's lists are in terms of behaviour mostly "generators that are implicitly stored as a lazy linked list if necessary". So if you want to store stuff more compactly, or you want to index into the list (as opposed to looping over it), you need arrays. But even for arrays the story doesn't change much! Using the 'vector' library, actually all of the above examples work just fine, with no unnecessary intermediate vectors because of some intelligent fusion rules, if you put `V.` before the list-related function names.
- kragen 5y agoHaskell is #1 for generality but #0 for clarity, though I have to admit that some of my Python examples aren't exactly shining exemplars either. But if I write code in Haskell I can only call it from Haskell (which wasn't something I mentioned in my original comment, but is important). I think there's an underlying tension between generality and clarity. Clarity is when the code can't do things that aren't immediately obvious upon reading it. Generality is when it can. (There's a bit of squirrely equivocation here about what kinds of "thing" is being done, and what sense of "can" is meant, which is why they're just in tension and not really opposite, but I think there's some truth too.)
- tomsmeding 5y ago> But if I write code in Haskell I can only call it from Haskell (which wasn't something I mentioned in my original comment, but is important). Right, that's a downside. I believe there is a way in which you can call Haskell code from C, but I've never seen anyone use it myself. > I think there's an underlying tension between generality and clarity. You're on to something here. C++ has the same problem, where the syntax itself is context dependent: `a * b;` could be a multiplication if `a` is a variable, or a variable definition if `a` is a type. Also template meta-programming, and overloading and {con,des}tructors in general. (Of course, Haskell has the overloading thing even more -- though the containment of IO helps matters quite a bit in my opinion.) Golang explicitly chose to go the clarity way, and it got them some love and plenty of flak. Maybe one should just conclude from this that Haskell is not a great language for corporate environments. On the other hand, I think it's great for small-team development due to its expressivity and generality. But these two claims do not contradict each other: not every language is good for every purpose.
- secondcoming 5y ago> Because of Python's better orthogonality, you can factor out the lazy boolean sequence generator into a function of its own if that's a useful thing to do: You can do the same in C++: static bool isEven(int x) { return x % 2 == 0; } bool foo(const std::vector<int>& v) { return v.end() != std::find_if(v.begin(), v.end(), isEven); }
- kragen 5y agoNot the same; no sequence.