4 ms·
each is definitively transferable for many languages. Javascript has Array.map(), which is almost the same: var numbers = [1, 4, 9]; var roots = numbe
by icebraining 14y ago
each is definitively transferable for many languages.
Javascript has Array.map(), which is almost the same:
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
/* roots is now [1, 2, 3], numbers is still [1, 4, 9] */
C# has IEnumerable.Select():
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
/* squares is [1, 4, 9, 16, ...] */
Python has map(), which isn't OOP but accomplishes mostly the same:
names = ["mary", "john"]
caps = map(lambda name: name.upper(), names)
- LeafStorm 14y agoThe examples you give are equivalents to Enumerable#map, not Enumerable#each. In JavaScript, the closest equivalent to #each is Array.forEach(). In C# and Python, while methods equivalent to #each may exist (I'd have to double-check the docs to be sure), the recommended way to accomplish the same functionality as #each is...a for loop.
- noblethrasher 14y agoC# doesn't have an Enumerable.ForEach (but it does have a List.ForEach). More significantly, it has a Parallel.ForEach which is recommended for iterations that can be done in parallel.
- SideburnsOfDoom 14y ago> C# doesn't have an Enumerable.ForEach It's trivial to add it as an extension method though. I've seen it done, and I wanted to punch them for using needlessly overcomplex idioms. It's discussed here http://stackoverflow.com/questions/225937/foreach-vs-somelist-foreach/226299#226299 http://stackoverflow.com/questions/225937/foreach-vs-somelis... > More significantly, it has a Parallel.ForEach which is recommended for iterations that can be done in parallel. Yes and no. I've seen Parallel.ForEach misused more often than I've seen it used right. If you have a small ( < 16) number of loop iterations then don't bother with Parallel.ForEach. If each of those items to process is time-consuming then use tasks and Task.WaitAll for them to complete. Where Parallel.ForEach works well is where there are a very large number of iterations, and the scheduler can split batches of them up between cpu cores, and even tune the batch size as the run progresses. That's just not going to happen when there are 5 loop iterations.
- Argorak 14y ago#each can be seen as special case of #map where the mapped function returns its argument.
- djacobs 14y ago#each and #map are not meant to be the same thing. #each in any language is meant only for side-effects. If you only care about the return value, #map is a much better choice. (Similarly, if you only care about the return value but want many items condensed into one "reduced" item, you want #reduce.)