digitalmars.D.learn - Learning to use ranges instead of arrays
- Bob Tolbert (21/21) Jul 20 2014 I find myself writing this code too much and i'm curious what D
- John Colvin (10/31) Jul 20 2014 Even without ranges, you can do this:
- Bob Tolbert (6/15) Jul 20 2014 Oh, I see that now. Guess when I saw it returned a SortedRange, I
- Ivan Kazmenko (5/5) Jul 20 2014 Also, there is std.array.array for the ranges you want to convert
I find myself writing this code too much and i'm curious what D idiom I am missing. given a list of files (or any strings) and then maybe I want to sort them and maybe I don't. string [] fileList; ... fill list if (sort) { string [] tempList; foreach(filename; sort(fileList)) { tempList ~= filename; } fileList = tempList; } foreach(filename, fileList) { ... do something; } but I know this is ugly code, so I'm curious as to how to make it better. I suspect it is something very simple, about switching everything I do to 'ranges', but I can't see it yet. Thanks for any input, Bob
Jul 20 2014
On Sunday, 20 July 2014 at 16:02:05 UTC, Bob Tolbert wrote:I find myself writing this code too much and i'm curious what D idiom I am missing. given a list of files (or any strings) and then maybe I want to sort them and maybe I don't. string [] fileList; ... fill list if (sort) { string [] tempList; foreach(filename; sort(fileList)) { tempList ~= filename; } fileList = tempList; } foreach(filename, fileList) { ... do something; } but I know this is ugly code, so I'm curious as to how to make it better. I suspect it is something very simple, about switching everything I do to 'ranges', but I can't see it yet. Thanks for any input, BobEven without ranges, you can do this: string [] fileList; ... fill list if (sort) sort(fileList); foreach(filename, fileList) { ... do something; } because sort works in-place.
Jul 20 2014
On Sunday, 20 July 2014 at 16:11:03 UTC, John Colvin wrote:Even without ranges, you can do this: string [] fileList; ... fill list if (sort) sort(fileList); foreach(filename, fileList) { ... do something; } because sort works in-place.Oh, I see that now. Guess when I saw it returned a SortedRange, I stopped reading and missed the bit about the underlying array also being sorted. Thanks for the quick help, Bob
Jul 20 2014
Also, there is std.array.array for the ranges you want to convert to arrays. For example, if "a" is an array, "a.map!(x => x * 2).array" produces an new array of doubled values (as opposed to a lazy range produced by std.algorithm.map).
Jul 20 2014