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.
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.)
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.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.
(Heh, even Malbolge Unshackled is likely Turing-complete.)
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.Accumulate, surprisingly enough, accumulates by default:
return accumulate(x.begin(), x.end(), 0); std::accumulate(v.cbegin(), v.cend(), decltype(*v.cbegin()){});
:) :) :) #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;
}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.
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.
Why would I want to add by default?
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.
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.
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).
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.
(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;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.
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.
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."
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.
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.
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]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.
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.
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.
x = np.arange(0,10,1)
print(x[x%2==0])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.
(0..10).select{it.even?} 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.It's a matter of preference, but I'd still risk ambiguity and name collision, especially when you go beyond std:: (like boost stuff).
list.iter().sum()
ezpzC++ 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.
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 :)
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.
https://stackoverflow.com/questions/9981607/array-foreach-ru...
We tested the normal loop vs. the clever loop. Performance-wise, the normal loop blew the doors off the clever loop.
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.
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.
In C# it is just
return numbers.Sum();The one-liner approach tends to include an explicit type declaration (Or turbofish), `iter()`, and `collect()`, at minimum.
x.iter().sum()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.
In Rust you would probably just write: x.iter().sum()
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...
Only collections of numeric types (including arrays) have Sum.
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enu...
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...
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.
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.
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)
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.
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. fold_left(x, 0, _1 + _2)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?".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)