DEV Community

Discussion on: List Comprehension in D

Collapse
 
beatbutton profile image
Mitchell Ferree

The built-in module "itertools" has support for Cartesian products, iterator flattening, and more. Comparing one tool in Python, list comprehensions, to arbitrary iterator adaptors in D is disingenuous.

Python has built-in "map" and "filter" functions as well, should you prefer those over comprehensions.

Collapse
 
jessekphillips profile image
Jesse Phillips • Edited

Possibly, do you have examples?

What is the Pythonic way? I showed D idioms.

Collapse
 
jessekphillips profile image
Jesse Phillips

Just stumbled acrossed this

medium.com/better-programming/how-...

The issue I see with this is chaining multiple operations. In the example he stores the result before the next operation.

Let's look at an alternative way to make it readable.

// Original breakup, but written in D
auto numbers = [1,2,3,4,5,6];

auto odd_numbers = filter!(n=> n % 2 == 1)(numbers);

auto squared_odd_numbers = map!(n=> n * n)(odd_numbers);

// fold is another name used for reduce 
auto total1 = fold!((acc, n)=> acc + n)(squared_odd_numbers, 0);

// chain operation 
auto total2 = numbers
    .filter!(n=> n % 2 == 1)
    .map!(n=> n * n)
    .fold!((acc, n)=> acc + n)(0);

// Name the lambda operation 
alias odds = x => x % 2 == 1;
alias square = x => x * x;
alias sum = (acc, n)=> acc + n;

auto total3 = numbers
    .filter!odds
    .map!square 
    .fold!sum(0);


assert(total1 == total2);
assert(total3 == total2);

The language isn't the driving force for readability here.

If you look closely D does provide usage challenges since I introduced the use of alias. Explaining its need would be more technical than lambda : is that a bad thing? I don't know.