March 31, 2020 Convert program to 2020: replace foreach loop with map, filter and friends | ||||
---|---|---|---|---|
| ||||
I'd like to convert the following program to 2020 standards (i.e, replace the foreach block with a one-line code). I've tried much and I failed. This is the code that works (1990s style) -- import std; void main() { immutable URL = r"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"; immutable LOCAL = r"local-file"; immutable country = "Poland"; download(URL, LOCAL); auto file = File(LOCAL, "r"); int i = 0; foreach(rec; file.byLine()) { auto x = rec.splitter(',').array; if (i == 0) { // Print Header writeln(x); } else if (x[1] == country) { // Print Country Line writeln(x); break; } i++; } } -- |
March 31, 2020 Re: Convert program to 2020: replace foreach loop with map, filter and friends | ||||
---|---|---|---|---|
| ||||
Posted in reply to User | On Tuesday, 31 March 2020 at 04:00:28 UTC, User wrote: > I'd like to convert the following program to 2020 standards (i.e, replace the foreach block with a one-line code). I've tried much and I failed. Here is how I'd do it. Because the program downloads and then reads the local file unconditionally, I replaced it with byLine. This allows it to process the data as it is being downloaded, without first waiting to download everything. import std; void main() { immutable URL = r"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"; immutable country = "Poland"; URL .byLine .map!(line => line.splitter(",")) .enumerate .filter!(t => t.index == 0 || t.value.dropOne.front == country) .map!(t => t.value) .take(2) .each!writeln; } |
Copyright © 1999-2021 by the D Language Foundation