News for hackers. Stuff that matters.
Re:Clever code is probably the worst code you could write by porphyra on Tuesday May 21, 2024 @06:43PM (#40434949)
I also find that, in C++,

    int sum = 0;
    for (int i = 0; i < n; ++i)
        sum += x[i];
    return sum
is a lot easier to understand than

    return std::accumulate(x.begin(), x.end(), 0, [](int a, b) {return a + b;});
Yet, the latter is considered more correct and better, with static analysis like cppcheck telling you to use the latter. It does have many advantages, like no mutable variables lying around, but gee it is annoying to read.
Re:Clever code is probably the worst code you could write by nine_k on Tuesday May 21, 2024 @07:39PM (#40435607)
It's mostly the problem of the language, and not of the approach.

In a more expressive language you can omit the explicit slicing (x.begin(), x.end()) and have the compiler derive the lambda's signature for you, so you'd write something like reduce(x, (a, b) => a + b), or even fold (+) x, with all the same static analysis and efficient compilation guarantees.

Re:Clever code is probably the worst code you could write by knome on Tuesday May 21, 2024 @09:25PM (#40436380)
I think it's mostly a fad issue. Normal loops and if statements are just as possible to hit with a static analyzer. But the very fact that they look easy makes a certain kind of programmer see them as beneath them. They want the complex looking code, even if it's functionally equivalent and semantically no more sound. They like the visual noise and complexity of it. It rubs their egos the right way.
Re:Clever code is probably the worst code you could write by nine_k on Tuesday May 21, 2024 @10:06PM (#40436630)
Loops are more complex. They expose more implementation details, worse, they "expose" irrelevant details. Unless your CPU is very simple, like a Cortex M0, the C compiler will likely rewrite your loop using vector instructions (think MMX / SSE / Neon), leaving an unrecognizable mess where a neat loop with an index used to be.

C was invented to match PDP-9 and PDP-11, and it matches them beautifully. Constructs like *a++ = *b++ directly compile to instructions like MOV (R1)+, (R2)+, etc. But however much I may like the beauty and simplicity of the PDP-11 architecture, it belongs to the past, or maybe to simplest MCUs. C no longer matches hardware all that well, and especially the idioms of C from classic books written 30-40 years ago don't match modern hardware woefully, if you care about the last bit of performance. (If you don't, take C#, Java, Go, even V8; they are plenty fast with JIT compilers.)

Re:Clever code is probably the worst code you could write by knome on Wednesday May 22, 2024 @12:54PM (#40443194)

    00106   template<typename _InputIterator, typename _Tp, typename _BinaryOperation>
    00107     _Tp
    00108     accumulate(_InputIterator __first, _InputIterator __last, _Tp __init,
    00109            _BinaryOperation __binary_op)
    00110     {
    00111       // concept requirements
    00112       __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
    00113       __glibcxx_requires_valid_range(__first, __last);
    00114 
    00115       for (; __first != __last; ++__first)
    00116     __init = __binary_op(__init, *__first);
    00117       return __init;
    00118     }
    
    https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.0/stl__numeric_8h-source.html#l00108
It's just a loop.

The compiler is doing all of the same transformations regardless of whether you use the higher order function or just write a loop yourself.

--------------

    _STD_BEGIN
    _EXPORT_STD template <class _InIt, class _Ty, class _Fn>
    _NODISCARD _CONSTEXPR20 _Ty accumulate(const _InIt _First, const _InIt _Last, _Ty _Val, _Fn _Reduce_op) {
        // return noncommutative and nonassociative reduction of _Val and all in [_First, _Last), using _Reduce_op
        _STD _Adl_verify_range(_First, _Last);
        auto _UFirst      = _STD _Get_unwrapped(_First);
        const auto _ULast = _STD _Get_unwrapped(_Last);
        for (; _UFirst != _ULast; ++_UFirst) {
    #if _HAS_CXX20
            _Val = _Reduce_op(_STD move(_Val), *_UFirst);
    #else // ^^^ _HAS_CXX20 / !_HAS_CXX20 vvv
            _Val = _Reduce_op(_Val, *_UFirst);
    #endif // ^^^ !_HAS_CXX20 ^^^
        }
        return _Val;
    }
    
    https://github.com/microsoft/STL/blob/63354c3fa9c1fb2ab1fccb58c47d23c6af1c290f/stl/inc/numeric#L24
Also just a loop in MS' standard lib.
Re:Clever code is probably the worst code you could write by nine_k on Wednesday May 22, 2024 @05:29PM (#40446834)
Try -O2 or -O3 like you would in a release build.

See https://stackoverflow.com/a/50786881

Re:Clever code is probably the worst code you could write by knome on Wednesday May 22, 2024 @06:13PM (#40447350)
Optimization levels aren't going to care if you're using std::accumulate or not.

They'll either analyze the loop directly, or they'll analyze it after munging it through the template function instantiation code and inlining the results of the template function.

After that, both are doing what you originally said, lifting the C into an abstract form and analyzing it for whether parallel computation can be applied.

Hell, the code to SSE enabled asm examples they give in the comment you link are just plain for loops.

Re:Clever code is probably the worst code you could write by danlugo92 on Wednesday May 22, 2024 @03:37PM (#40445343)
Nice dissertation but loops is all you need.
Re:Clever code is probably the worst code you could write by nine_k on Wednesday May 22, 2024 @05:34PM (#40446889)
From a certain standpoint, a Turing machine is all you need.

(Heh, even Malbolge Unshackled is likely Turing-complete.)

Re:Clever code is probably the worst code you could write by danlugo92 on Wednesday May 22, 2024 @07:56PM (#40448486)
You got me
Re:Clever code is probably the worst code you could write by a_t48 on Tuesday May 21, 2024 @06:53PM (#40435079)
We now have

       return std::reduce(x.begin(), x.end());
Which is a little cleaner and is even faster (compiler is free to do the additions in any order). https://en.cppreference.com/w/cpp/algorithm/reduce - it looks like even the `accumulate` example can be made simpler with `std::plus`. I prefer the `reduce` option for a number of reasons, but understand why someone might not.
Re:Clever code is probably the worst code you could write by floxy on Tuesday May 21, 2024 @07:34PM (#40435557)
>the `accumulate` example can be made simpler with `std::plus`

Accumulate, surprisingly enough, accumulates by default:

    return accumulate(x.begin(), x.end(), 0);
Re:Clever code is probably the worst code you could write by MathMonkeyMan on Tuesday May 21, 2024 @08:24PM (#40435971)
Just make sure you're accumulating integers and not doubles!
Re:Clever code is probably the worst code you could write by a_t48 on Wednesday May 22, 2024 @12:41AM (#40437411)
Obviously, you have to use

   std::accumulate(v.cbegin(), v.cend(), decltype(*v.cbegin()){});
:) :) :)
Re:Clever code is probably the worst code you could write by floxy on Thursday May 23, 2024 @12:52AM (#40450601)

  #include<cstdio>
  #include<numeric>
  #include<vector>
  
  using namespace std;
  
  template <class T, template<class> class Cont>
  T sum(Cont<T> x)
  {
    return accumulate(x.begin(), x.end(), (T)0);
  }
    
  int main(int argc, char *argv[])
  {
    vector<double> ds({1.1, 2.2, 3.3, 4.4}); 
    vector<float> fs({1.1f, 2.2f, 3.3f, 4.4f});
    vector<int> is({1, 2, 3, 4});
    vector<unsigned long long> ulls({1ul, 2ul, 3ul, 4ul});

    printf("doubles: %f\n",sum(ds));
    printf("floats: %f\n",sum(fs));
    printf("ints: %d\n",sum(is));
    printf("ulls: %llu\n",sum(ulls));

    return 0;
  }
Re:Clever code is probably the worst code you could write by autoexecbat on Tuesday May 21, 2024 @07:05PM (#40435218)
I think most people would be thinking "hmm now I need to read what 'reduce' mean in this context"
Re:Clever code is probably the worst code you could write by jacoblambda on Tuesday May 21, 2024 @07:19PM (#40435397)
At least in my experience in the C++ world there is a general expectation that you learn the "standard algorithms" and prefer them over the alternatives unless you have a specific reason not to.

For example: outside the C++ ecosystem, most people probably would stare blank faced if they saw `std::rotate` in a codebase but it's basically a meme at this point in the C++ space.

Ex: https://www.youtube.com/watch?v=UZmeDQL4LaE

Re:Clever code is probably the worst code you could write by a_t48 on Tuesday May 21, 2024 @07:17PM (#40435364)
For at least the first time, yeah.
Re:Clever code is probably the worst code you could write by j1elo on Tuesday May 21, 2024 @07:17PM (#40435358)
Look at that link:

  2,4,6) ...
  These overloads participate in overload resolution only if
  std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> is true.
  std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> is true.
std::is_execution_policy_v? std::decay_t? std::remove_cvref_t?

Really, this madness with C++ needs to stop. People who work on newer versions of the language might be very conservative with the language syntax itself, but they clearly decided having carte blanche to adding an infinite amount of stuff to the standard library.

Could someone please force them to stop, somehow? The whole rest of the industry would be thankful.

Re:Clever code is probably the worst code you could write by lupire on Tuesday May 21, 2024 @07:18PM (#40435382)
That's terrible! The main operation, addition, is completely hidden magic! But the completely trivial calls to .begin() and .end() are explicit!

Why would I want to add by default?

Re:Clever code is probably the worst code you could write by jcelerier on Tuesday May 21, 2024 @08:40PM (#40436074)
> The main operation, addition, is completely hidden magic

the main operation is reduction which is fairly basic computer science and taught in any non-BS curriculum - https://en.wikipedia.org/wiki/Reduction_operator (or https://en.wikipedia.org/wiki/Fold_(higher-order_function) which is the standard way to introduce this concept ; check in particular the table showcasing all the implementations in various languages). The standard reduction for a set of numbers to a number that is likely going to be the very first example in your textbook is addition.

Re:Clever code is probably the worst code you could write by Dylan16807 on Tuesday May 21, 2024 @09:26PM (#40436390)
The reduction is explicit. That's not what the complaint is about. And it's more about implementation than the actual result.

The actual operation is addition. I don't care if it's the first example, that doesn't mean you should hide it.

Imagine if print did hello world by default.

Re:Clever code is probably the worst code you could write by o11c on Tuesday May 21, 2024 @08:57PM (#40436181)
std::ranges::fold_left (since C++23) can take a range directly instead of a separated pair of iterators, and requires the explicit add.
Re:Clever code is probably the worst code you could write by psychoslave on Wednesday May 22, 2024 @09:32AM (#40440749)
Maybe the idea is that you overload your favored default as a + operator? Even more baffling certainly, but at this point I wouldn’t even be surprised this was considered a compelling argument in the mind of whoever settled this API choice. :D
Re:Clever code is probably the worst code you could write by constantcrying on Wednesday May 22, 2024 @11:28AM (#40442184)
What is hidden? It's a reduce on + starting with 0, hardly anything subtle.
Re:Clever code is probably the worst code you could write by vlovich123 on Tuesday May 21, 2024 @08:26PM (#40435982)
> and is even faster (compiler is free to do the additions in any order)

Is that actually true? I'm not even sure how hypothetically removing ordering requirements would help you extract performance, let alone any compilers that could do anything with that today. Unless the standard library were to auto-parallelize the reduction, but I doubt they'd do that because the overhead of starting threads would be quite costly for anything but the absolute largest ranges since C++ doesn't have a thread pool sitting idly for you (not to mention that the docs for the function don't mention any thread safety requirements for the BinaryOp and Init which would be required for any such optimization).

Re:Clever code is probably the worst code you could write by a_t48 on Tuesday May 21, 2024 @10:53PM (#40436885)
The linked page has benchmarks - I'd have to go dig into godbolt to see why it's faster. The standard library can actually auto-parallelize, but you have to opt in (see the ExecutionPolicy argument).

Edit: I don't know how to dig into the actual implementation of std::reduce on godbolt - it's not inlined. I think the sibling comment has it right though - one can do adds of four at a time with whatever SIMD extensions are available.

Re:Clever code is probably the worst code you could write by im3w1l on Tuesday May 21, 2024 @08:38PM (#40436065)
I think relaxing the ordering requirement let's you use simd something like this (semi-pseudo code)

  (a, b, c, d) = (0, 0, 0, 0);
  for(int i = 0; i < n; i += 4) {
    (a, b, c, d) += (arr[i], arr[i+1], arr[i+2], arr[i+3]);
  }
  return a + b + c + d;
Re:Clever code is probably the worst code you could write by mjcohen on Wednesday May 22, 2024 @01:08PM (#40443385)
What if n is not a multiple of 4? There is a trick I can't recall at the moment for handling this with a case statement on n mod 4 at the end to wrap this up.
Re:Clever code is probably the worst code you could write by jbboehr on Thursday May 23, 2024 @03:46AM (#40451753)
Re:Clever code is probably the worst code you could write by vlovich123 on Wednesday May 22, 2024 @01:37PM (#40443736)
Are you sure that the compiler doesn’t autovectorize a simple loop into this form anyway? This is kind of the defacto scenario for that pass.
Re:Clever code is probably the worst code you could write by im3w1l on Wednesday May 22, 2024 @03:23PM (#40445124)
This transformation is only legal if order of summation doesn't matter. So the compiler can do it for ints, but not floats.
Re:Clever code is probably the worst code you could write by vlovich123 on Wednesday May 22, 2024 @09:54PM (#40449501)
Applying std::reduce to floats would be a similarly bad idea for having the compiler do it, except people will write it without thinking. Of course, people always struggle with writing correct floating point so I doubt it makes things better or worse, but it’s conceptually the library equivalent of -fast-math (which coincidentally would also auto-vectorize the loop but can impact more than just that).
Re:Clever code is probably the worst code you could write by im3w1l on Thursday May 23, 2024 @02:51PM (#40458414)
Using fast math in one particular expression is way different and less risky than doing it globally.
Re:Clever code is probably the worst code you could write by zarathustreal on Tuesday May 21, 2024 @09:16PM (#40436310)
You answered the question yourself..can you at least edit your comment so you won’t confuse otherwise correctly oriented computer science practitioners?

The commutative property is fundamental to understanding algebraic structures and fast parallel processing. If a binary operation is commutative over a given set then, yes, a proper compiler will parallelize it. No, it will not necessarily use OS threads directly one to one, that’s usually not a consideration even for a naive approach.

Re:Clever code is probably the worst code you could write by Xeoncross on Tuesday May 21, 2024 @06:59PM (#40435149)

    int sum = 0;
    for (int i = 0; i < n; ++i)
        sum += x[i];
Pretty much looks the same in all C-like languages. I've written that in Java, Go, TypeScript, PHP, etc...

On the other hand, that second 'clever' example always looks different for every stupid language. It's std::accumulate in C++, streams in Java, list comprehension in python, etc...

Clear is better than clever.

Re:Clever code is probably the worst code you could write by floxy on Tuesday May 21, 2024 @08:08PM (#40435843)
One man's clever is another man's clear.

https://web.archive.org/web/20180619022832/http://webdocs.cs...

"The instructions corresponding to a conventional language might be expressed something like the following:

Select an apple from the box. If it is good, set it aside in some place reserved for the good apples; if it is not good, discard it. Select a second apple; if it is good put it in the reserved place, and if it is not good discard it. ... Continue in this manner examining each apple in turn until all of the good apples have been selected. In summary, then, examine the apples one at a time starting with the first one we pick up and finishing with the last one in the box until we have selected and set aside all of the good apples. On the other hand the instructions corresponding to an array language could be stated simply as “Select all of the good apples from the box.” Of course, the apples would still have to be examined individually, but the apple-by-apple details could be left to the helper.

Conventional programming languages may be considered then “one-apple-at-a-time” languages with machine languages being a very primitive form, whereas array languages may be considered “all-the-apples-at-once” languages. In two of the following three sections we shall consider the array languages APL and its “modern dialect” J with an intervening section giving a short discussion of the array language Nial which was influenced by APL."

Re:Clever code is probably the worst code you could write by bsza on Tuesday May 21, 2024 @08:42PM (#40436091)
> Pretty much looks the same in all C-like languages

Because it’s ancient; that doesn’t necessarily make it better or clearer. Look at it like you’ve never seen it before. It has an entire line of boilerplate smack bang in the middle. Sure, your brain filters it out because you’re used to it, but it’s still fugly. And it’s prone to typos/copypaste errors like all boilerplate.

Re:Clever code is probably the worst code you could write by Xeoncross on Tuesday May 21, 2024 @09:36PM (#40436456)
Yes, but it's also not going anywhere.

I don't consider replacing a common loop convention with what amounts to a randomly-generated sentence or two of syntax and letters in each language to be an improvement.

Re:Clever code is probably the worst code you could write by theshrike79 on Wednesday May 22, 2024 @01:52AM (#40437743)
Just the '++i' instead of 'i++' brought my reading that code to a halt and I had to start deciphering if it actually changes the operation of the loop.
Re:Clever code is probably the worst code you could write by sgarland on Tuesday May 21, 2024 @06:58PM (#40435132)
That is somewhat annoying, yes. I'm a huge fan of Python's list comprehension, but it's generally accepted to be a normal part of the language, and IMO, more readable:

    print([x for x in range(10) if not x % 2])
    [0, 2, 4, 6, 8]
vs.

    l = []    
    for x in range(10):
        if not x % 2:
            l.append(x)
    print(l)
    [0, 2, 4, 6, 8]
Re:Clever code is probably the worst code you could write by okanat on Tuesday May 21, 2024 @07:42PM (#40435622)
Call me crazy, but I find the second example more readable.

The first example is long line and you have to go back and forth to understand it. The second example is a single top down pass.

Re:Clever code is probably the worst code you could write by crazygringo on Tuesday May 21, 2024 @08:02PM (#40435792)
Agreed, me as well.

The second example reflects how my brain thinks and the intuitive order of what has to happen.

In the first example, it's all out of order.

Re:Clever code is probably the worst code you could write by sgarland on Tuesday May 21, 2024 @08:03PM (#40435795)
I’m sure I’m biased, since I code mainly in Python. List/dict comprehensions read the same to me as the longer form, just more concisely. This can be taken too far, and you can wind up with horribly obtuse one-liners that are just awful.
Re:Clever code is probably the worst code you could write by okanat on Tuesday May 21, 2024 @08:21PM (#40435945)
I write and maintain code in a bunch of languages. Rust has risen to the first place, C is the close second followed by C++ and Python.

All of the languages except C have similar iterator-based stuff that let you write one liners and often with lambdas. I dislike them all. They give way too much leeway and encourage many developers to try to prove how clever they are.

Once you have to debug the code containing them, all of the complexity of the syntactic sugar comes crashing down on you. The debugger starts jumping to weird places, sometimes even optimized out parts of the standard libraries while for loops usually stay debugable.

Re:Clever code is probably the worst code you could write by floxy on Tuesday May 21, 2024 @08:17PM (#40435917)

    x = np.arange(0,10,1)
    print(x[x%2==0])
Re:Clever code is probably the worst code you could write by f33d5173 on Tuesday May 21, 2024 @08:56PM (#40436176)
I've seen people complain about wrapping a comprehension over multiple lines, but I can't imagine packing them all in one. In your example, I would spread it out over five lines, so it would be at as long as the imperative case.

While I like python, I think the unusual order that components of a comprehension are written is to its detriment. It would make more sense if they were in the same order in both examples. The python ternary has a similar issue.

Re:Clever code is probably the worst code you could write by glandium on Tuesday May 21, 2024 @09:16PM (#40436312)
You chose the one example that doesn't need a list comprehension. print(list(range(0, 10, 2)))
Re:Clever code is probably the worst code you could write by sgarland on Tuesday May 21, 2024 @09:27PM (#40436395)
Good call.
Re:Clever code is probably the worst code you could write by psychoslave on Wednesday May 22, 2024 @11:42AM (#40442339)
With ruby 3.4 (prior to that `_1` should be used instead of `it`):

    (0..10).select{it.even?}
Re:Clever code is probably the worst code you could write by psychoslave on Wednesday May 22, 2024 @11:47AM (#40442400)
Also not that the result is `[0, 2, 4, 6, 8, 10]`, unlike the behavior of Python which exclude the value explicitely passed in parameter from the represented range.
Re:Clever code is probably the worst code you could write by haolez on Tuesday May 21, 2024 @06:48PM (#40434998)
I like C++, but I don't understand this tradition of keeping these annoying namespaces prefixed to everything. Just get rid of those std::, foo::bar::whatever::, etc from your code and make it more readable. Use the "use" clause. It's very rare for such names to be ambiguous in the same file, unless I'm missing some bigger picture here.
Re:Clever code is probably the worst code you could write by porphyra on Tuesday May 21, 2024 @07:01PM (#40435168)

    using namespace std;
is considered kinda bad since you don't want your namespace to be polluted with a bunch of std stuff. For example if you have `int count` lying around somewhere you'd want to be able to call `std::count` without fear of it being shadowed.
Re:Clever code is probably the worst code you could write by haolez on Tuesday May 21, 2024 @07:16PM (#40435345)
But ambiguity gives you readability. And if a "count" variable clashes with the function name, it's trivial for the compiler to catch this and warn you.

It's a matter of preference, but I'd still risk ambiguity and name collision, especially when you go beyond std:: (like boost stuff).

Re:Clever code is probably the worst code you could write by tialaramex on Tuesday May 21, 2024 @07:22PM (#40435428)
Because of bad design decisions, a whole pile of unrelated stuff lives in the std namespace, and the disambiguation probably isn't what you wanted, so this can silently cause surprises.
Re:Clever code is probably the worst code you could write by devnullbrain on Tuesday May 21, 2024 @07:19PM (#40435389)
It gives you readability. It's not what I'm used to, so it feels like reading French to me. Generally, if I see something without a namespace, it has a local scope.
Re:Clever code is probably the worst code you could write by kalkr on Tuesday May 21, 2024 @07:33PM (#40435546)
Traditional C style for is terrible compared to what you can do with iterators in my opinion, but idk if C++ has those.

    list.iter().sum()
ezpz
Re:Clever code is probably the worst code you could write by phailhaus on Tuesday May 21, 2024 @07:22PM (#40435435)
The other thing nice about the second style is that it's much easier to skim when part of a larger function, since it's a single type-checked statement. Keeps you from doing too much in it too.
Re:Clever code is probably the worst code you could write by williamcotton on Tuesday May 21, 2024 @07:36PM (#40435571)
I haven’t written any C++ since the 90s. That is unrecognizable. Is that an anonymous function?
Re:Clever code is probably the worst code you could write by nine_k on Tuesday May 21, 2024 @07:47PM (#40435671)
C++98 should be forgotten as a bad dream. C++17 is almost a sane and convenient language (as long as you remember about the boiling depths into which you can fall if you're careless).

C++ will live for very long, like Fortran. And also like Fortran, there now must be a serious and uncommon reason to start a new project in it.

Re:Clever code is probably the worst code you could write by pklausler on Tuesday May 21, 2024 @08:08PM (#40435840)
Why does one need an uncommon reason to begin development in Fortran?
Re:Clever code is probably the worst code you could write by nine_k on Tuesday May 21, 2024 @09:48PM (#40436530)
For instance, the much narrower circle of experts. Usually if you do need Fortran, it means you're going to run numerical code on a huge cluster with RAM in terabytes and cores in the thousands, so the developers you're looking for should understand parallelization very well (and how modern Fortran does it), know words like MPI and Slurm, etc. Beside that, knowledge of the common numerical methods and libraries is expected. This is a relatively unusual setup. Few job listings mention it.

If you just want some highly parallel numerical code, but a GPU with several tens of gigs of RAM would suffice, you just take Numpy, or PyTorch, or other such library, wrapped into Python. You suddenly have a wide circle of developers, plethora of references, and no lower chances to publish in a prestigious journal than if you'd taken Fortran :)

Re:Clever code is probably the worst code you could write by floxy on Tuesday May 21, 2024 @07:40PM (#40435611)
Re:Clever code is probably the worst code you could write by sesuximo on Tuesday May 21, 2024 @07:08PM (#40435251)
Imo it doesn’t matter at all. Both are fine. Surely there are more pressing things out there to think about!
Re:Clever code is probably the worst code you could write by lupire on Tuesday May 21, 2024 @07:20PM (#40435398)
Why would you not use std::sum(x) ?
Re:Clever code is probably the worst code you could write by quotemstr on Tuesday May 21, 2024 @06:48PM (#40434999)
One pet peeve of mine is people using std::for_each instead of a simple loop
Re:Clever code is probably the worst code you could write by jraph on Tuesday May 21, 2024 @07:22PM (#40435432)
Same in JS. I once worked with someone who would use [].forEach and didn't like for loops because functional good, iterative loops bad. It was essentially in the coding style of the project and the for version would be rejected in MRs.

I don't miss this.

IMHO [].forEach just essentially expresses the same thing as a regular for loop, although in a more verbose and convoluted way that is also likely very inefficient because a JS compiler probably can't optimize away the function call per iteration, because of the very dynamic nature of JS. forEach probably has its use when you specifically need to call an existing function on each element, but I don't otherwise see the appeal.

Re:Clever code is probably the worst code you could write by lupire on Tuesday May 21, 2024 @07:33PM (#40435547)
You are making a strong evidence-free claim about what JS compilers don't do.

https://stackoverflow.com/questions/9981607/array-foreach-ru...

Re:Clever code is probably the worst code you could write by Teckla on Tuesday May 21, 2024 @08:14PM (#40435888)
At $WORK we use Mozilla Rhino for some JavaScript processing.

We tested the normal loop vs. the clever loop. Performance-wise, the normal loop blew the doors off the clever loop.

Re:Clever code is probably the worst code you could write by MrJohz on Wednesday May 22, 2024 @12:54AM (#40437470)
Rhino is a very uncommon engine though. It has its niche, but if you're developing for simpler engines like that, then you typically know that in advance and know what considerations you're going to need to make for that.

When it comes to performance, lessons that apply to Rhino are unlikely to apply to more mainstream engines.

EDIT: That's not to say that everyone should use map and forEach all the time, just that your benchmarks are unlikely to be relevant to most JS devs outside of your specific use-case.

Re:Clever code is probably the worst code you could write by jraph on Wednesday May 22, 2024 @01:23AM (#40437598)
You call "strong claim" something I prefixed with "probably"?

It seems for loops in your link can be slower because .length (a function in disguise) is repeatedly called. I do save .length when writing JS. .length calls has been hard to optimize and it can't hurt too much to cache it at the start of the loop.

Now it's good news if today's engines are able to optimize most of .forEach. The amount of optimization JS engines can do never ceases to amaze me and yes, any performance claim in JS needs to be constantly reviewed and checked at the time it is discussed.

You can't take a "probably" as gospel. Still, it was a bit lazy of me to not re-check, I guess being called out was warranted.

Re:Clever code is probably the worst code you could write by neonsunset on Tuesday May 21, 2024 @06:54PM (#40435092)
C++ makes this (and many other things!) needlessly painful.

In C# it is just

    return numbers.Sum();
Re:Clever code is probably the worst code you could write by vlovich123 on Tuesday May 21, 2024 @08:30PM (#40436005)
Same for Rust.
Re:Clever code is probably the worst code you could write by the__alchemist on Tuesday May 21, 2024 @10:38PM (#40436816)
I tend to use for loops in Rust for this reason; simple, and understandable by anyone who's programmed in an imperative language.

The one-liner approach tends to include an explicit type declaration (Or turbofish), `iter()`, and `collect()`, at minimum.

Re:Clever code is probably the worst code you could write by cptroot on Wednesday May 22, 2024 @10:39PM (#40449807)
FYI I think you've misinterpreted the parent. To my eyes it looks like they're agreeing that Rust makes summing a list easy using combinations. For example, this is how I would do it in Rust:

  x.iter().sum()
Re:Clever code is probably the worst code you could write by vlovich123 on Thursday May 23, 2024 @04:02AM (#40451877)
I think they’ve understood and are claiming that a simple loop is cleaner than what you wrote. I’m not sure how since that 1 line communicates what’s happening at a high level with 1 word “sum” whereas a loop requires me to read the loop to confirm it’s a plain summation.

This sounds like someone complaining that the concepts they learned when they were first starting out are the only concepts that programming languages should introduce which is silly - technology evolves as we find better and new ways of accomplishing old tasks.

Re:Clever code is probably the worst code you could write by tialaramex on Tuesday May 21, 2024 @07:19PM (#40435391)
Where did "numbers" come from, and why are you so sure you can Sum() it? The original C code offered has some data structure (perhaps an array?) called x. Do C# arrays have a Sum method? I don't think so.

In Rust you would probably just write: x.iter().sum()

Re:Clever code is probably the worst code you could write by nyssos on Tuesday May 21, 2024 @07:42PM (#40435639)
> Do C# arrays have a Sum method? I don't think so.

It's not literally a method (it's not, for instance, in the vtable of some array class), but as far as their API is concerned, yeah, they do: https://github.com/dotnet/runtime/blob/main/src/libraries/Sy...

Re:Clever code is probably the worst code you could write by neonsunset on Tuesday May 21, 2024 @07:22PM (#40435436)
C# arrays don't. However, C# arrays are IEnumerable<T>, which does.
Re:Clever code is probably the worst code you could write by lupire on Tuesday May 21, 2024 @07:32PM (#40435535)
IEnunerable<T> of course does not have Sum.

Only collections of numeric types (including arrays) have Sum.

https://learn.microsoft.com/en-us/dotnet/api/system.linq.enu...

Re:Clever code is probably the worst code you could write by masfuerte on Tuesday May 21, 2024 @07:35PM (#40435564)
So you can't use IEnumerable<T>.Sum if T is a custom type implementing operator+ ?
Re:Clever code is probably the worst code you could write by neonsunset on Tuesday May 21, 2024 @07:49PM (#40435690)
You could, but .Sum is a little more specific than that - it is non-overflowing sum.

Historically, constraining generic arguments on addition was problematic - the full feature set of numeric types was "lifted" to be fully representable through generics only recently[0].

With that said, there is an open proposal[1] to introduce additional generic math overloads to IEnumerable<T> methods, but it hasn't seen much activity as the existing overloads cover most commonly used numeric types already.

[0]: https://learn.microsoft.com/en-us/dotnet/standard/generics/m...

[1]: https://github.com/dotnet/runtime/issues/64031

Re:Clever code is probably the worst code you could write by lupire on Tuesday May 21, 2024 @07:29PM (#40435509)
This comment makes no sense. You dismissed the C# code, and then wrote the same thing in Rust, but with an extra non-conceptually-meaningful boilerplate step.

May as well ask, "where did x come from, and why are you so sure you can iter().sum() it?"

C# has generic types, so yes, C# arrays of numbers have a Sum method.

https://stackoverflow.com/questions/2419343/how-to-sum-up-an...

Don't make bold dismissive comments about things you are ignorant of. It makes you look Blubby.

Re:Clever code is probably the worst code you could write by tialaramex on Tuesday May 21, 2024 @07:59PM (#40435773)
The C# code ends up relying on LINQ, it's interesting how many C# programmers don't even think about that, either anything they work on already uses LINQ or they just reflexively bring it in everywhere they write C#

You'll see that a few of those SO comments actually say they're relying on LINQ to make that work. The array type doesn't have such a method itself.

So, in reality although many C# programmers will think of this as "correct" it just won't even compile... except if there's already LINQ.

Re:Clever code is probably the worst code you could write by neonsunset on Tuesday May 21, 2024 @08:21PM (#40435949)
There is nothing wrong with System.Linq just like there's nothing wrong with Rust's std::iter::Iterator. If anything, this makes writing Rust use the existing muscle memory if you have C# experience and vice versa.

The performance profile of LINQ, while much maligned, has been steadily improving over the years and, in the example of Sum itself, you actually do want to use it because it will sum faster than open-coded loop[0].

I do have grievances regarding LINQ still - my (non-negotiable) standpoint is that Roslyn (C# compiler) must lower non-escaping LINQ operations to open-coded loops, inline lambdas at IL level and similar, making it zero-cost - .NET (IL compiler/runtime) provides all the tools necessary to match what Rust's zero-cost-ish iterator expressions offer and there just needs to be more political will in the Roslyn teams to do so. Because of this, I'm holding my breath waiting for DistIL[1] to be production-ready which does just that.

[0]: https://github.com/dotnet/runtime/blob/main/src/libraries/Sy...

[1]: https://github.com/dubiousconst282/DistIL

(I don't understand what you mean by "it won't compile", because it will, in most cases System.Linq namespace is already referenced anyway, either through global usings or at the top of the file)

Re:Clever code is probably the worst code you could write by tialaramex on Wednesday May 22, 2024 @07:40AM (#40439772)
> (I don't understand what you mean by "it won't compile", because it will, in most cases System.Linq namespace is already referenced anyway, either through global usings or at the top of the file)

The "in most cases" is doing all the lifting here. Rust's Iterator is in the prelude. Even if you #![no_std] you get the core prelude which has core::iter::Iterator. You would need to explicitly write code to tell Rust "No, I don't want the prelude" to get rid of it, I'm sure people do that, otherwise it wouldn't be possible, but few enough that I've never seen it.

But in C# there is no such promise. In most (but not all) real world C# projects somebody already brought in LINQ. If you're using a technology that gives you a "ready to go" standard C# project template it undoubtedly folds in LINQ too. But it's not actually provided by the language and that's a meaningful gap.

Notably in several of the playground type tools, since LINQ is not there by default this won't work - like I said it won't compile and it doesn't suggest "Oh you need LINQ" because the C# compiler doesn't provide such suggestions.

Re:Clever code is probably the worst code you could write by neonsunset on Wednesday May 22, 2024 @09:01AM (#40440412)
It's difficult to talk to someone committed to misreading the replies.

LINQ aka IEnumerable/Iterator methods are usually imported by default, something like with prelude. As others said, they are part of standard library.

I'm not sure what you are arguing against either but whatever your criticism is - it is misplaced as C# and Rust roughly belong to the same Venn diagram of features against commonly held beliefs.

You can test it yourself:

    sudo apt install dotnet-sdk-8.0
    mkdir TestConsole && cd TestConsole
    dotnet new console
And then just paste/echo the following to Program.cs:

    var numbers = Enumerable.Range(0, 10).ToArray();
    var sum = numbers.Sum();
    Console.WriteLine(sum);
This will compile. If that's not enough, then it's likely Rust the language is not for you either and you may want to use something like Go for the time being.
Re:Clever code is probably the worst code you could write by latentsea on Tuesday May 21, 2024 @09:24PM (#40436364)
Usage of LINQ is usually taken for granted.
Re:Clever code is probably the worst code you could write by wvenable on Tuesday May 21, 2024 @09:28PM (#40436404)
LINQ is just part of .NET standard library along with the very collections we are talking about. I'm not sure why one would care about the distinction.
Re:Clever code is probably the worst code you could write by GrantMoyer on Tuesday May 21, 2024 @09:42PM (#40436494)
If you use C++23's ranges and Boost Lambda and sacrifice your better judgement, you can get it down to:

    fold_left(x, 0, _1 + _2)
Re:Clever code is probably the worst code you could write by leetcrew on Tuesday May 21, 2024 @10:41PM (#40436829)
the readability issue here is in part that function arguments are purely positional in c++.

a little over the top for this simple example, but you can always create local variables to document intention.

  auto initVal = 0;
  auto accumulateOp = [](int a, b) {return a + b;};
  return std::accumulate(x.begin(), x.end(), initVal, accumulateOp);
I'd prefer to see a for each loop over algorithms functions in such simple cases, but I'd prefer almost anything over direct indexing when it isn't necessary. when I see that in new code, my first thought is always "what am I missing here?".
Re:Clever code is probably the worst code you could write by globular-toast on Wednesday May 22, 2024 @03:34AM (#40438290)
sum(x) is easiest to read. If your language doesn't provide that as standard just define it yourself. In general you should always be idiomatic, though. If every C++ developer understands the accumulate version then use that.
Re:Clever code is probably the worst code you could write by constantcrying on Wednesday May 22, 2024 @11:24AM (#40442134)
That is just a question of what you are used to. The "functional style" example is very obvious to a person who is familiar with that style. In fact if the rest of the code base is in a similar style it is the easier one to understand.

There is nothing inherent which makes either better or cleverer than the other.

(Also the first one is incomplete, as "n" is not defined, making the later more self contained)