Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 28 additions & 10 deletions index.dd
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,27 @@ $(DIVC intro, $(DIV, $(DIV,
)
$(DIVID your-code-here-default,
$(RUNNABLE_EXAMPLE
$(RUNNABLE_EXAMPLE_STDIN
The D programming language
Modern convenience.
Modeling power.
Native efficiency.)
----
// Compute average line length for stdin
void main()
{
import std.range, std.stdio;

auto sum = 0.0;
auto count = stdin.byLine
.tee!(l => sum += l.length).walkLength;

writeln("Average line length: ",
count ? sum / count : 0);
}
----
)
$(EXTRA_EXAMPLE
$(RUNNABLE_EXAMPLE_STDIN 2.4 plus 2.4 equals 5 for sufficiently large values of 2.)
----
// Round floating point numbers
Expand Down Expand Up @@ -243,20 +264,17 @@ Modern convenience.
Modeling power.
Native efficiency.)
----
#!/usr/bin/env rdmd
import std.range, std.stdio;

// Compute average line length for stdin
void main()
{
ulong lines = 0, sumLength = 0;
foreach (line; stdin.byLine())
{
++lines;
sumLength += line.length;
}
import std.range, std.stdio;

auto sum = 0.0;
auto count = stdin.byLine
.tee!(l => sum += l.length).walkLength;
Copy link
Member

@CyberShadow CyberShadow Jun 17, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even shorter would be:

size_t count = 0;
double sum = stdin.byLine.tee!(l => count++).sum;

but I guess that demonstrates fewer range features.

Copy link
Member Author

@PetarKirov PetarKirov Jun 18, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think that would compile, unless you add a map!(l => l.length) between the tee and the sum.

/d912/f975.d(7): Error: template std.algorithm.iteration.sum cannot deduce function from argument types !()(Result), candidates are:
/opt/compilers/dmd2/include/std/algorithm/iteration.d(4663): std.algorithm.iteration.sum(R)(R r) if (isInputRange!R && !isInfinite!R && is(typeof(r.front + r.front)))
/opt/compilers/dmd2/include/std/algorithm/iteration.d(4674): std.algorithm.iteration.sum(R, E)(R r, E seed) if (isInputRange!R && !isInfinite!R && is(typeof(seed = seed + r.front)))

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, you're right :)


writeln("Average line length: ",
lines ? cast(double) sumLength / lines : 0.0);
count ? sum / count : 0);
}
----
))
Expand Down