Python's features, which requires D
Dennis Ritchie via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri May 22 19:36:11 PDT 2015
On Friday, 22 May 2015 at 05:31:38 UTC, Ali Çehreli wrote:
> Here is my attempt:
>
> import std.stdio;
> import std.algorithm;
> import std.conv;
> import std.range;
>
> void main()
> {
> // Replace 'none' with 'all' to activate.
> version (none) {
> const n = 5;
>
> auto a = stdin
> .byLine
> .map!(l => l.splitter.map!(to!int).array)
> .take(n);
>
> writeln(a);
> writeln("-----");
> }
>
> {
> const n = 6;
>
> auto a = iota(n)
> .map!(i => chain([2].replicate(i),
> [1],
> [0].replicate(n - i - 1)));
>
> writefln("%(%(%s %)\n%)", a);
> writeln("-----");
> }
>
> {
> const x = [ 1, 2, 3, 4, 5, 6 ];
>
> writeln(x.stride(2));
> writeln(x.dropOne.stride(2));
> writeln("-----");
> }
>
> {
> // The internet does not need another fizz buzz. :p
> }
> }
>
> Ali
Yes, it looks pretty good :) Thanks. But...
It seems to me that D lacks features that allow you to write
function readln/readln.strip/readln.split just inside the lambda.
stdin.byLine is a good feature, but it captures the entire input
stream, which I should handle all or take lambdas function
take(n) n lines and then still handle all of these lines right
away. Ie stdin.byline used everywhere is not always convenient!
For example, the code in Python looks quite natural:
a = [[int(j) for j in input().split()] for i in range(n)]
About D-code, I can not say:
>auto a = stdin
> .byLine
> .map!(l => l.splitter.map!(to!int).array)
> .take(n);
I can call the map with the existing array:
import std.stdio, std.algorithm, std.conv, std.array;
void main()
{
auto a = [1, 2, 3];
auto b = a.map!(c => c ~
readln.split.map!(to!int).array).array;
writeln(b);
}
-----
http://rextester.com/MBUMHI13858
But I can not call the readln n times without a map:
import std.stdio, std.conv, std.algorithm, std.array, std.range;
void main() {
auto a = [1, 2, 3];
auto b = [readln.split.map!(to!int).array].take(3);
writeln(b);
}
-----
http://rextester.com/KCJ9346
Ie readln function cycle is needed for, another lambda or revised
map! Is there a function in Phobos?
More information about the Digitalmars-d-learn
mailing list