Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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)


The 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.


C# 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.


> 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-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.


#each can be seen as special case of #map where the mapped function returns its argument.


#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.)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: